Problem: 389. 找不同
思路
给定两个字符串 s 和 t ,它们只包含小写字母。 字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。 请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y"
输出:"y"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母
解题方法
- 我们可以使用哈希表来统计字符串 s 中每个字符的出现次数,然后再遍历字符串 t,逐个减去哈希表中对应字符的出现次数。最后剩下的字符就是被添加的字母。
- 计算两个字符串的 ASCII 码值的和并相减,然后得到多出来的字符,可以分别对两个字符串中的每个字符进行 ASCII 码值的累加,然后将两个累加值相减,最后将差值转换为字符。(参考官方思路)
复杂度
时间复杂度:
这段代码的时间复杂度为 ,其中 是字符串 t 的长度。在哈希表统计字符出现次数和遍历字符串 t 时,都只需遍历一次。
空间复杂度:
空间复杂度为 ,因为哈希表的大小是固定的,不随输入数据规模变化。
Code
法一:
class Solution(object):
def findTheDifference(self, s, t):
count = defaultdict(int)
for char in s:
count[char] += 1
for char in t:
count[char] -= 1
if count[char] < 0:
return char
return ""
法二:
class Solution(object):
def findTheDifference(self, s, t):
ascii1 = sum(ord(char) for char in s)
ascii2 = sum(ord(char) for char in t)
ascii_difference = ascii2 - ascii1
difference_char = chr(ascii_difference)
return difference_char