leetcode 389. Find the Difference

Given two strings s and t which consist of only lowercase letters.

String t is generated by random shuffling string s and then add one more letter at a random position.

Find the letter that was added in t.

Example:

Input:
s = "abcd"
t = "abcde"

Output:
e

Explanation:
'e' is the letter that was added.

复制代码
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        """
        s = "abcd" t = "abcde" =>e
        s = "abcd" t = "abcdee" =>ee
        s = "abcd" t = "abcdfe" =>ef?fe?
        s = "a" t = "" =>a
        s = "ab" t = "" =>ab?ba?
        # use dict to map t
        # sub the letter of t in s
        """
        letter_cnt = {}
        for c in t:
            if c not in letter_cnt:
                letter_cnt[c] = 0
            letter_cnt[c] += 1
        for c in s:
            if c in letter_cnt:
                letter_cnt[c] -= 1
                assert letter_cnt[c] >= 0
        return "".join(c*letter_cnt[c] for c in letter_cnt)
复制代码

用排序:

复制代码
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        # abcd, abcde
        # afjz, abcfjz
        # afjx, abcfjxyz
        s = sorted(s)
        t = sorted(t)
        ans = ""
        i = j = 0
        while i< len(s):
            if s[i] != t[j]:
                ans += t[j]
                j += 1
            else:
                i += 1
                j += 1
        return ans+"".join(t[j:])
复制代码

如果仅仅有一个char不一样则可以使用xor:

复制代码
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        # if just only one char is different
        ans = 0
        for c in s:
            ans ^= ord(c)
        for c in t:
            ans ^= ord(c)
        return chr(ans)
复制代码
复制代码
class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        # if just only one char is different        
        return chr(sum(ord(i) for i in t)-sum(ord(i) for i in s))
复制代码

用求和也可以!

 

posted @   bonelee  阅读(304)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-03-15 mongodb c++ driver安装踩坑记
2017-03-15 赴美生子诚实签
2017-03-15 签证存款证明——如果在签证前不久刚存入的资金,最好能够提供资金来源的证明,强调资金肯定不是借来的,是自己家的,这样的证明包括企业的营业执照和盈利的证明(账本),炒股的进出账单、有活期进出帐的存折,父母亲的收入证明等
2017-03-15 量子计算的基本原理——本质上是在操作薛定谔的猫(同时去运算和操作死+不死两种状态)
点击右上角即可分享
微信分享提示