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

LeetCode 2273: Find Resultant Array After Removing Anagrams

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

基本資料
#

難易度: easy 第一次嘗試:2026-01-29

  • 提交紀錄:Accepted(一次通過)

解題思路
#

刪掉 words[i] 之後,它後面的字的「前一個」變成 words[i - 1]。被刪掉的字跟 words[i - 1] 是異位詞,而異位詞有傳遞性,所以跟被刪的字比、跟 words[i - 1] 比結果一樣。

因此由左到右掃,只跟最後一個留下來的字比:不是異位詞就留下。判斷異位詞用排序後的字串(Hash Table 模板五)。

我的解法
#

我當時從右往左,用 Counter 比較相鄰的字,一樣就 pop。這裡改成由左到右建新的陣列:

class Solution:
    def removeAnagrams(self, words: List[str]) -> List[str]:
        res = []
        for w in words:
            if not res or sorted(res[-1]) != sorted(w):
                res.append(w)
        return res

複雜度
#

時間 O(n · L log L),L 是字的長度,空間 O(n · L)。

要特別避免的錯誤
#

  • 在迴圈中 pop 會改變 index,從右往左做才安全;建新陣列更簡單。

面試口說整理
#

刪掉一個字後,下一個字會跟它前一個比;因為異位詞有傳遞性,結果等於只跟最後留下的字比。我由左到右掃,跟最後留下的字排序後不一樣就留下。時間 O(n L log L)。

相關文章

LeetCode 3545: Minimum Deletions for At Most K Distinct Characters
·1 分鐘
LeetCode Easy Greedy Hash-Table String Sorting Counting
LeetCode 3545 解題筆記:要減少種類就得整種刪掉,從出現次數最少的開始刪
LeetCode 3606: Coupon Code Validator
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 3606 解題筆記:先過濾合法的優惠券,再用(類別順序, code)排序;字元範圍要包含 z、Z、9
LeetCode 389: Find the Difference
·1 分鐘
LeetCode Easy Hash-Table String Bit-Manipulation Sorting
LeetCode 389 解題筆記:t 比 s 多一個字元,把兩個字串的所有字元 XOR 起來,成對的抵消,剩下的就是多的那個
LeetCode 242: Valid Anagram
·1 分鐘
LeetCode Easy Hash-Table String Sorting
LeetCode 242 解題筆記:兩個字串的字元次數完全相同就是 anagram,用 Counter 比較或排序後比較
LeetCode 3803: Count Residue Prefixes
·1 分鐘
LeetCode Easy Hash-Table String
LeetCode 3803 解題筆記:邊掃邊把字元加進集合,前綴的不同字元數等於長度 % 3 就算一個
LeetCode 3090: Maximum Length Substring With Two Occurrences
·1 分鐘
LeetCode Easy Sliding-Window Hash-Table String
LeetCode 3090 解題筆記:「求最長」的滑動視窗,剛加進來的字元超過 2 次就縮左邊