[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]
相关推荐
xxxxxue几秒前
Windows 通过 右键菜单 调用 Python 脚本
开发语言·windows·python·右键菜单
Wonderful U1 分钟前
基于 Django Channels 与 WebSocket 的实时聊天室:群聊、私聊、离线消息与持久化存储全实现
python·websocket·django
Wonderful U2 分钟前
Python+Django实战|校园二手闲置交易平台:从实名认证到交易闭环的完整校园电商解决方案
开发语言·python·django
爱吃苹果的梨叔6 分钟前
2026年分布式坐席系统怎么选:指挥中心与调度大厅指南
python
小白学大数据6 分钟前
全站链接深度爬取:Python GUI 事件绑定 + 运行时动态过滤实现思路
开发语言·爬虫·python
菜菜的顾清寒11 分钟前
力扣HOT100(51) 动态规划-单词拆分
算法·leetcode·动态规划
zhangfeng113311 分钟前
超算/曙光DCU集群 昆山站 htc /public 目录全解
人工智能·python·机器学习
Maydaycxc11 分钟前
Excel/WPS 自动化实战:科学计数法、千张表格循环处理、打包交付的多工具对比
python·自动化·excel·wps·rpa
py小王子11 分钟前
Nature 期刊图复刻|带内嵌边缘密度的多组时序回归拟合图
python·nature·期刊图片复现
玫幽倩12 分钟前
2026盘古石取证决赛(手机取证)
python·电子取证·计算机取证·聊天软件·手机取证·fic