LeetCode——找不同

LeetCode——找不同

题目描述:
给定两个字符串 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

解法一:

我们将两个字符串分别用两个字典存储起来,字符作为键,该字符的出现次数作为值。
然后我们遍历dic_t,判断该字符是否在dic_s中,如果不在就说明他是加进去的字符,返回即可;如果在,则判断其在两个字典中对应的值是否相同(即出现次数),如果相同则继续遍历,如果不同则说明他是加进去的字符,返回即可。

解法二:

我们先将两个字符串排序好;
再遍历比较,若两个字符不同则说明是新加的,返回即可。

解法一python代码:

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        dic_s = {}
        dic_t = {}
        for str_s in s:
            if str_s in dic_s:
                dic_s[str_s] += 1
            else:
                dic_s[str_s] = 1
        for str_t in t:
            if str_t in dic_t:
                dic_t[str_t] += 1
            else:
                dic_t[str_t] = 1
        for key in dic_t.keys():
            if key in dic_s:
                if dic_t[key] == dic_s[key]:
                    continue
                else:
                    return key
            else:
                return key


解法二python代码:

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        s = sorted(s)
        t = sorted(t)
        for i in range(len(t)):
            if i < len(s):
                if t[i] == s[i]:
                    continue
                else:
                    return t[i]
            else:
                return t[i]


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值