Find the Difference

Given two stringssandtwhich consist of only lowercase letters.

Stringtis generated by random shuffling stringsand then add one more letter at a random position.

Find the letter that was added int.

Example:

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

Output:
e

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

1. XOR

两个相同的数异或为0,0和任何数异或为任何数,例如:y ^ x ^ x = y; x ^ x = 0。注意字母要使用ord,最后结果用chr返回字母

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

Last updated

Was this helpful?