[LeetCode][Python]389. 找不同

python 复制代码
简单
给定两个字符串 s 和 t ,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
示例 1:
输入:s = "abcd", t = "abcde"
输出:"e"
解释:'e' 是那个被添加的字母。
示例 2:
输入:s = "", t = "y"
输出:"y"
提示:
0 <= s.length <= 1000
t.length == s.length + 1
s 和 t 只包含小写字母

解题思路:

正确的思路:

计数方法:对每个字母出现次数进行了统计
错误的思路:

按位比对

正确解法

python 复制代码
def count_letters(s, t):
    result1 = {}
    result2 = {}
    for i in s:
        if i in t:
            # Return the value for key if key is in the dictionary, else default.
            # 返回索引i对应的键的值
            result1[i] = result1.get(i, 0) + 1
    for j in t:
        if j in t:
            result2[j] = result2.get(j, 0) + 1
    print(result1)
    print(result2)
    # 分类讨论
    # 情况一:键存在
    for key, value in result1.items():
        if value != result2.get(key):
            return key
    # 情况二:键不存在
    # 遍历第二个字典的键
    for key in result2:
        # 如果第二个字典的值在第一个字典中不存在,则将键添加到结果列表中
        if key not in result1:
            return key

print(count_letters("abcd", "acde"))

错误解法

python 复制代码
def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        n = len(t)
        s = s + " "
        i = 0

        while 1:
            if s[i]== t[i]:
                i += 1
            else:
                print(t[i])
                break
        return t[i]
相关推荐
tlwlmy11 小时前
python excel图片批量导出
开发语言·python·excel
ValhallaCoder11 小时前
hot100-矩阵
数据结构·python·算法·矩阵
那年我七岁11 小时前
android ndk c++ 绘制图片方式
android·c++·python
Java后端的Ai之路11 小时前
【Python教程10】-开箱即用
android·开发语言·python
We་ct11 小时前
LeetCode 48. 旋转图像:原地旋转最优解法
前端·算法·leetcode·typescript
爱尔兰极光11 小时前
LeetCode--长度最小的子数组
算法·leetcode·职场和发展
深蓝电商API11 小时前
异步爬虫中代理池的并发管理
开发语言·爬虫·python
B站计算机毕业设计超人12 小时前
计算机毕业设计PySpark+Hive+Django小红书评论情感分析 小红书笔记可视化 小红书舆情分析预测系统 大数据毕业设计(源码+LW+PPT+讲解)
大数据·人工智能·hive·爬虫·python·spark·课程设计
有一个好名字12 小时前
力扣-电话号码组合
算法·leetcode·职场和发展
黄筱筱筱筱筱筱筱12 小时前
7.适合新手小白学习Python的异常处理(Exception)
java·前端·数据库·python