[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]
相关推荐
ocean21031 分钟前
2025-2026年Python大厂面试高频问题
python·面试·面试经验
xn713323 分钟前
实测 Codex CLI 0.154.0:response.failed 为什么会被 idle timeout waiting for SSE 覆盖
python·openai
李高钢24 分钟前
Python Flask 框架入门:从零搭建你的第一个 Web 应用
前端·python·flask
码农学院28 分钟前
外贸独立站GEO实战:用 Python 自动生成多语言 llms.txt 和 Schema 站点地图
人工智能·python·chatgpt·geo·geo优化·ai优化aio
jsjzsl233 分钟前
独立自由度框架下核聚变的本体论本质与商业化技术新路径
人工智能·python·算法
Thomas.Sir37 分钟前
第45课:TensorFlow|异常检测实战【工业设备数据故障识别模型搭建】
人工智能·python·tensorflow
土司大王38 分钟前
LeetCode hot100——51.N 皇后:Java 回溯模板、列与对角线剪枝、O(n!) 复杂度分析
java·leetcode·剪枝
数商云企43 分钟前
2026年西安电商智能客服开发选数商云企,技术稳交付快
大数据·python
Patrick在香港1 小时前
Python 分析香港 AQHI 归档 1644 天:同一天的空气,早上 8 点报 3,下午 5 点报 10
开发语言·python·数据分析·api·restful·数据可视化·开放数据
SamChan901 小时前
Python批量处理PDF踩坑实录:中文编码、字体内嵌、多栏排版与内存占用
python·单片机·ai·pdf·机器翻译