[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]
相关推荐
不脱发的程序猿11 分钟前
红利ETF量化策略
人工智能·python·ai·程序员·量化交易·etf·策略回测
Apok'16 分钟前
零基础学Python量化(1):研究大纲与流程
python·机器学习·金融·数据挖掘·数据分析
鬓戈19 分钟前
llmproxy 系统开发目的和基本功能
人工智能·python
卷无止境36 分钟前
ARM与x86、x64的能效之争:指令集只是故事的开头
后端·python
2601_962885721 小时前
如何用 Python 计算溃疡指数(Ulcer Index)?
开发语言·python
benchmark_cc1 小时前
如何为 QuantDash Python SDK 编写一个最小化的连接验证脚本?
python·数据分析·pandas·量化交易·股票数据·quantdash
程序边界1 小时前
顶刊级论文配图全流程:用 Python 复刻 Nature/Science 风格图表
开发语言·python
BD_Marathon1 小时前
【RAG项目】01、RAG项目案例介绍
python
好焊孙辉1 小时前
螺柱焊机哪家质量好
python·fpga开发
STLearner2 小时前
KDD 2026 | (2月轮)时空数据(Spatial-Temporal)论文总结时空【下】(人群移动,城市科学(资源调度,)
大数据·人工智能·python·深度学习·机器学习·语言模型·数据挖掘