[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]
相关推荐
love530love1 分钟前
【笔记】ComfyUI KeyError: ‘tensorrt‘ 错误的完整解决方案
windows·笔记·python·pycharm
zzywxc7876 分钟前
解锁 Rust 开发新可能:从系统内核到 Web 前端的全栈革命
开发语言·前端·python·单片机·嵌入式硬件·rust·scikit-learn
极客数模41 分钟前
2025年MathorCup 大数据竞赛明日开赛,注意事项!论文提交规范、模板、承诺书正确使用!2025年第六届MathorCup数学应用挑战赛——大数据竞赛
大数据·python·算法·matlab·图论·比赛推荐
PieroPc1 小时前
用Python Streamlit Sqlite3 写一个简单商品管理系统
数据库·python·sqlite·streamlit
小白银子1 小时前
零基础从头教学Linux(Day 55)
java·linux·服务器·python
程序员小远1 小时前
Appium+python+unittest搭建UI自动化框架
自动化测试·软件测试·python·测试工具·ui·appium·测试用例
MavenTalk1 小时前
如何根据不同的场景选择YOLO相应的基座模型
python·yolo·yolo11n·yolo11m·yolo11s·yolo11x
神奇的代码在哪里1 小时前
使用python开发任天堂gameboy模拟器|pyboy开发实践
python·宝可梦·pyboy·gameboy模拟器·任天堂掌机模拟器
坚持就完事了2 小时前
正则表达式与Python的re模块
python·正则表达式
Alex艾力的IT数字空间2 小时前
基于PyTorch和CuPy的GPU并行化遗传算法实现
数据结构·人工智能·pytorch·python·深度学习·算法·机器学习