声明:
今天是第86道题。给定两个字符串 s 和 t,找2者不同的那个字母。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除
(手动比心ღ( ´・ᴗ・` ))
正文
题目:给定两个字符串 s 和 t,它们只包含小写字母。字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。请找出在 t 中被添加的字母。
示例:
输入: s = "abcd" t = "abcde" 输出: e 解释: 'e' 是那个被添加的字母。
解法1。先构建好s中每个字符和其频数的对应关系作为比较基准,再逐一遍历t,找到没有在s中出现过或者频数对应不相等的字符并返回,代码如下。
执行用时: 28 ms, 在Find the Difference的Python提交中击败了97.36% 的用户
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
s_dict = {}
for i in s:
if i not in s_dict:
s_dict[i] = 1
else:
s_dict[i] += 1
for i in t:
if i in s_dict and s_dict[i] == t.count(i):
continue
else:
return i
return -1
解法2。只用1层循环,遍历26个字母,判断在s和t中出现频数是否一致,代码如下。
执行用时: 24 ms, 在Find the Difference的Python提交中击败了100.00% 的用户
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
alpha = "qwertyuiopasdfghjklzxcvbnm"
for i in alpha:
if s.count(i) != t.count(i):
return i
return 0
# 其实上述还有优化版本,就是只遍历t,因为t是s的超集
for i in set(t):
if s.count(i) < t.count(i):
return i
return 0
解法3。思路非常之清奇,就是遍历s,把t中和s一样的元素统统删掉,返回最后不一样的那个元素,代码如下。
执行用时: 36 ms, 在Find the Difference的Python提交中击败了60.57% 的用户
class Solution(object):
def findTheDifference(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
for i in s:
t = t.replace(i,'',1)
return t
结尾
解法1:原创
解法2&解法3:LeetCode