389. 找不同
- 题号:力扣389
- 知识点:哈希
- 目标完成度:41/150
- 总结
题干:
思路:
- 1.首先对
s
和t
构造字典,得到其中出现的各个字符以及他们出现的次数。 - 2.然后遍历
t
所构造的字典(遍历t
是因为t
中的元素要多于s
) - 3.如果遍历到的某元素也在
s
中,并且出现的次数相等就跳过 - 4.如果遍历到的某元素也在
s
中,并且出现的次数不相等,那么t
多出的元素就是要找的不同 - 5.如果遍历到的某元素不在
s
中,把该元素也是要找的不同
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
d1 = collections.Counter(s)
d2 = collections.Counter(t)
ret = ''
for key, value in d2.items():
if key in d1:
if value == d1[key]:
continue
else:
for j in range(value - d1[key]):
ret += key
else:
for i in range(value):
ret += key
return ret