[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]
相关推荐
抓不住时间的沙3 分钟前
Butterfly主题 5.7 导航栏添加相册同时设置相册入口密码
css·python·node.js
风合星语15 分钟前
2026 机器人工程实例(五):让 Allegro Hand 在 MuJoCo 中完成接触抓取——抓取状态机、稳定抬升与受控释放
c++·python·机器人·仿真
隐擎fox1 小时前
解构无感人机验证底层机制:行为生物轨迹采样、环境评分模型与自动化对抗实战
自动化测试·python·网络协议·tcp/ip·网络爬虫
Tisfy1 小时前
LeetCode 0836.矩形重叠:xy两方向分别看
数学·leetcode·题解·模拟
haidao0311 小时前
氙灯光源技术特性及其在光催化实验中的标准化应用研究
人工智能·python·能源
用户0332126663671 小时前
使用 Python 设置 Excel 行列自适应 【代码示例】
python·excel
Ticnix2 小时前
RAG 的坑不在检索,在"对齐":pgvector 实战手记
python·agent·全栈
kyrie_sakura2 小时前
python学习笔记14 -- FastAPI
笔记·python·学习·fastapi
青山木2 小时前
Hot 100 --- 最长递增子序列
java·数据结构·算法·leetcode·动态规划
春涧草茶2 小时前
慢就是快12-2三种访问权限|getter与setter|魔法方法
开发语言·python