Find the Difference

2023-07-16

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.

Solution

这题解法很多,首先说一下常规思路:统计最长的字符串(t)每个字符出现的次数(使用字典dic:字符-字符次数),然后遍历短的字符串(s),循环获得字符c,然后dic[c] = 字符次数 - 1,最后找出字典中次数为1的对应的字符

Python

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        dic_t = {}
        for item in t:
            dic_t[item] = dic_t.get(item,0) + 1
        
        for item in s:
            dic_t[item] = dic_t[item] - 1
        
        for item in t:
            if dic_t[item] == 1:
                return item

这题同样可以使用 XOR,或者只是将字符转换为对于对应的 ASCII 数值然后相减

XOR

class Solution(object):
    def findTheDifference(self, s, t):
        return chr(reduce(operator.xor, map(ord, s + t)))

相减

class Solution(object):
    def findTheDifference(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: str
        """
        ans = 0
        for c in t:
            ans = ans + ord(c)
        for c in s:
            ans = ans - ord(c)
        return chr(ans)