给定两个字符串s和t 它们只包含小写字母。字符串t是由s中的字母随机打乱之后在随机的一个位置添加一个字母生成的。请找出那个添加的字母。比如:s = abcdt = baedc输出:e请给出思路并提供代码
思路:
- 遍历字符串t,统计每个字母出现的次数,存储在字典中。
- 遍历字符串s,统计每个字母出现的次数,存储在字典中。
- 遍历字典,找到在t中出现次数多于在s中出现次数的字母,返回该字母。
代码实现如下:
def findTheDifference(s, t): s_dict = {} t_dict = {} for ch in t: if ch in t_dict: t_dict[ch] += 1 else: t_dict[ch] = 1 for ch in s: if ch in s_dict: s_dict[ch] += 1 else: s_dict[ch] = 1 for ch in t_dict: if ch not in s_dict or t_dict[ch] > s_dict[ch]: return ch
测试
s = "abcd" t = "baedc" print(findTheDifference(s, t)) # 输出:
原文地址: https://www.cveoy.top/t/topic/ipCw 著作权归作者所有。请勿转载和采集!