[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]
相关推荐
如何原谅奋力过但无声1 小时前
【灵神高频面试题合集06-08】反转链表、快慢指针(环形链表/重排链表)、前后指针(删除链表/链表去重)
数据结构·python·算法·leetcode·链表
deephub1 小时前
2026 RAG 选型指南:Vector、Graph、Vectorless 该怎么挑
人工智能·python·大语言模型·rag
狐狐生风3 小时前
使用 UV 创建并运行 Python 项目(完整步骤)
python·uv
噜噜噜阿鲁~3 小时前
python学习笔记 | 9.2、模块-安装第三方模块
笔记·python·学习
现代野蛮人3 小时前
【深度学习】 —— VGG-16 网络实现猫狗识别
网络·人工智能·python·深度学习·tensorflow
一个小猴子`3 小时前
Pytorch快速复习
人工智能·pytorch·python
wang3zc3 小时前
mysql如何提升InnoDB写入性能_对比MyISAM的写入锁机制
jvm·数据库·python
一起逃去看海吧4 小时前
工作流原理和实践
python
Ulyanov4 小时前
《从质点到位姿:基于Python与PyVista的导弹制导控制全栈仿真》: 可视化革命——基于 PyVista 的 3D 战场构建与实时渲染
开发语言·python·算法·3d·系统仿真
爱喝热水的呀哈喽4 小时前
一段即插即用的hypermesh命令行
开发语言·python