Skip to content

Latest commit

 

History

History
91 lines (72 loc) · 2.21 KB

0389._find_the_difference.md

File metadata and controls

91 lines (72 loc) · 2.21 KB

Navigation

Links

  1. https://leetcode.com/problems/find-the-difference/
  2. https://leetcode-cn.com/problems/find-the-difference/

Solution 1 Counter(本质是哈希表)做差集

from collections import Counter

class Solution:
    def findTheDifference(self, s, t):
        counter_s = Counter(s)
        counter_t = Counter(t)

        return list(counter_t - counter_s)[0]

class Solution:
    def findTheDifference(self, s, t):
        memo = {}

        for c in t:
            memo[c] = memo.get(c, 0) + 1
        
        for c in s:
            memo[c] = memo.get(c, 0) - 1

        for char, count in memo.items():
            if count == 1:
                return char

Solution 2 ASCII的和,相减

class Solution:
    def findTheDifference(self, s, t):
        return chr(sum(map(ord, t)) - sum(map(ord, s)))

Solution 3 遍历s,在t中删除s的每个字符

class Solution:
    def findTheDifference(self, s, t):
        for i in s:
            t = t.replace(i, '', 1)
        
        return t

Solution 4 抑或和ASCII

n ^ n == 0

class Solution:
    def findTheDifference(self, s, t):
        n = 0

        for c in t:
            n ^= ord(c)

        for c in s:
            n ^= ord(c)

        return chr(n)

Solution 5 排序后逐个比较

class Solution:
    def findTheDifference(self, s, t):
        s = list(s)
        t = list(t)
        s.sort()
        t.sort()

        for i in range(len(s)):
            if s[i] != t[i]:
                return t[i]
        
        return t[-1]