↓快轉到主要內容
  1. LeetCode/

LeetCode 389: Find the Difference

·1 分鐘· ·
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-08-23

  • 提交紀錄:Accepted → Runtime Error → Accepted

解題思路
#

跟 LC 136 一樣(Bit Manipulation):s 和 t 合起來,除了多的那個字元以外每個字元都出現偶數次,全部 XOR 起來就剩下它。也可以用 sum(ord(t)) - sum(ord(s))。

我的嘗試
#

第一次是排序後逐一比較,AC 了;之後試著改寫時有一版語法錯誤,最後改成用字元編碼的總和相減。

正確解法
#

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        x = 0
        for c in s + t:
            x ^= ord(c)
        return chr(x)

複雜度
#

時間 O(n),空間 O(1)。

要特別避免的錯誤
#

  • XOR 要對 ord 做,最後再 chr 轉回字元。

面試口說整理
#

兩個字串合起來,除了多的那個字元以外都出現偶數次,所以我把所有字元的編碼 XOR 起來,剩下的就是答案。時間 O(n)、空間 O(1)。

相關文章

LeetCode 242: Valid Anagram
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 242 解題筆記:兩個字串的字元次數完全相同就是 anagram,用 Counter 比較或排序後比較
LeetCode 290: Word Pattern
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 290 解題筆記:pattern 的字元和單字要一對一對應,用兩個方向的 dict 或比較 set 大小
LeetCode 383: Ransom Note
·1 分鐘
LeetCode Easy Hash-Table String Counting
LeetCode 383 解題筆記:ransomNote 每個字元的需求數量都不能超過 magazine 的數量;Counter 相減為空就成立
LeetCode 387: First Unique Character in a String
·1 分鐘
LeetCode Easy Hash-Table String Queue Counting
LeetCode 387 解題筆記:先計數,再從左到右找第一個次數是 1 的字元
LeetCode 405: Convert a Number to Hexadecimal
·1 分鐘
LeetCode Easy Math String Bit-Manipulation
LeetCode 405 解題筆記:負數先加上 2^32 變成補數,再每次取 4 個位元(% 16)轉成十六進位;0 要特別處理
LeetCode 409: Longest Palindrome
·1 分鐘
LeetCode Easy Hash-Table String Greedy
LeetCode 409 解題筆記:每個字元取偶數個放兩邊,只要有任何奇數次的字元,中間還能再放一個