题目:
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
解题思路
把字符串转换成字典,key为字符,value为字符出现的次数,由于t总是比s多一个字符,所以当s出现在t的时候,在t中可以使该字符的value-1,这样只剩下多出来字符的值,只要t中有字符的值不为0,那么多出来的字符就是题目所求。
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
d=dict()
d1=dict()
for ch in s:
d[ch]=d.get(ch,0)+1
for ch in t:
d1[ch]=d1.get(ch,0)+1
for i in s:
if i in d1:
d1[i]-=1
chs=[ch for ch,v in d1.items() if v!=0]
return ''.join(chs)