1. 问题描述:
给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y"
输出:"y"
示例 3:
输入:s = "a", t = "aa"
输出:"a"
示例 4:
输入:s = "ae", t = "aea"
输出:"a"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-the-difference
2. 思路分析:
分析题目可以知道我们使用哈希表解决,先遍历一下字符串s,统计一下各个字符出现的次数,然后遍历字符串t,若当前遍历的字符在哈希表中出现的次数为0说明当前的字符就是新加的字符直接返回该字符即可,若存在那么需要在字典的对应字符次数减1。
3. 代码如下:
import collections
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
# 哈希表计算s字符出现的次数然后判断遍历t即可
dic = collections.defaultdict(int)
for c in s:
dic[c] += 1
for c in t:
if dic[c] == 0: return c
dic[c] -= 1
return ""
版权声明:本文为qq_39445165原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。