给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母
Example:
Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added.
1:将s和t字符串用set()方法分别转为不包含重复元素的sSet和tSet集合。访问sSet集合,生成chaDic字典,字典中存放字母和其在s字符串中出现的次数,格式为character:count。访问tSet集合,判断字母在字典中是否存在,同时判断字母在t字符串中出现的次数与s字符串中次数是否一致
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
sSet = set(s)
tSet = set(t)
chaDic = {}
for i in sSet:
chaDic[i] = s.count(i)
for i in tSet:
if not chaDic.get(i) or t.count(i) != chaDic.get(i):
return i
return None
算法题来自:https://leetcode-cn.com/problems/find-the-difference/description/