[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]
相关推荐
盖伦发发2 分钟前
RAG 能跑≠能用:用 EDD 把 Eval 做成基础设施 (附源码)
人工智能·后端·python·功能测试
郝学胜_神的一滴21 分钟前
Python 高级编程 028:字典dict从入门到精通
python·ai编程
weixin_BYSJ198727 分钟前
springboot小区物业管理小程序---附源码45555
java·javascript·spring boot·python·django·flask·php
a-6262 小时前
三维重建的步骤-1(采集的是环绕物体均匀旋转一圈的视频)
python·pycharm·三维重建·metashape
Navigator_Z2 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
qq_22589174662 小时前
基于Flask的空气质量监测与预测分析系统
开发语言·后端·python·信息可视化·django·flask
Dxy12393102163 小时前
Python XPath position() 完整使用指南,避坑合集(lxml适用)
前端·javascript·python
AndrewHZ3 小时前
图像处理入门009 | OpenCV 图像读取与显示:imread/imshow 全解析
图像处理·python·opencv·算法·计算机视觉·图像显示
卷无止境3 小时前
手写 SQL 在 Tortoise ORM 里到底能派上什么用场
后端·python·fastapi
龙虾PRO3 小时前
2026 DeepSeek Harness 部署完整教程:npx 一键启动至 Python SDK 全流程接入
开发语言·python