Python实现"找不同"的一种方法 您所在的位置:网站首页 字母找不同的图片 Python实现"找不同"的一种方法

Python实现"找不同"的一种方法

2024-07-11 15:37| 来源: 网络整理| 查看: 265

给定两个字符串 s 和 t,它们只包含小写字母。

字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。

请找出在 t 中被添加的字母

Example:

Input: s = "abcd" t = "abcde" Output: e Explanation: 'e' is the letter that was added. 1:将s和t字符串用set()方法分别转为不包含重复元素的sSet和tSet集合。访问sSet集合,生成chaDic字典,字典中存放字母和其在s字符串中出现的次数,格式为character:count。访问tSet集合,判断字母在字典中是否存在,同时判断字母在t字符串中出现的次数与s字符串中次数是否一致 def findTheDifference(self, s, t): """ :type s: str :type t: str :rtype: str """ sSet = set(s) tSet = set(t) chaDic = {} for i in sSet: chaDic[i] = s.count(i) for i in tSet: if not chaDic.get(i) or t.count(i) != chaDic.get(i): return i return None

算法题来自:https://leetcode-cn.com/problems/find-the-difference/description/



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有