Python solution with detailed explanation


  • 0
    G

    Solution

    Find the Difference https://leetcode.com/problems/find-the-difference/

    Use 2 counters to find the missing character

    from collections import Counter
    class Solution(object):
        def findTheDifference(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: str
            """
            sc, tc = Counter(s), Counter(t)
            for x in tc:
                if x not in sc or sc[x] != tc[x]:
                    return x
            return
    

    Use XOR in an intelligent Manner

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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.