LeetCode 389 Find the Difference 解题报告

题目要求

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

扫描二维码关注公众号,回复: 5784416 查看本文章

        

        

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10657983.html