[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]
相关推荐
Tim_1013 分钟前
【LeetCode】338、比特位计数
c++·算法·leetcode
DanCheng-studio16 分钟前
毕设项目分享 大数据B站数据分析可视化系统
python·毕业设计·毕设
外收内放25 分钟前
数据分析(jupyter与pandas初体验)
python·学习
花间相见41 分钟前
【计算基础|网络04】—— HTTP接口实战(下):接口测试、鉴权与跨域排错
java·linux·人工智能·后端·python·计算机网络·postman
慧都小项42 分钟前
Python 跨文件重构怎么验证?PyCharm 用法查找、重构预览与测试流程
python·重构·pycharm·单元测试
SEO_juper1 小时前
2026年用Python批量审计XML Sitemap:揪出sitemap.xml中的“配置错误/死链/过期页“(附完整代码)
java·python·seo·外贸独立站·谷歌优化
钱栈up1 小时前
自动化多平台发布:脚本报FAIL时用三个信号判断真实状态
python
余槐i1 小时前
拆解 Agent 核心原理|从零动手实现简易 AI 智能体(三)
人工智能·python·fastapi·ai agent
程序员AlbertTu1 小时前
# Mantissa 使用教程 — Python 版与 C++ 版
c++·python·数值运算
童园管理札记1 小时前
从政策驱动到课堂落地:2026年“人工智能+教育”全景解读与技术实践指南
人工智能·python·深度学习·职场和发展·学习方法