题目要求
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
题目分析及思路
给定两个只由小写字母组成的字符串s和t,其中t是在s字符串组成元素的基础上再添加一个字母构成的。注意这里添加的字母可能和已有的字母重复。要求找到新添加的字母。可以使用collections.Counter统计每个字符串中不同字母出现的次数,然后遍历字典t的key,只要这个key不在字典s中或者该key对应的value不相等,则这个key就是我们要找的字母。
python代码
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
s = collections.Counter(s)
t = collections.Counter(t)
for k in t:
if k not in s or t[k] != s[k]:
return k