Valid Anagram 解題教學:3 種解法完整比較|LeetCode 242 Best Practice

Valid Anagram 解題教學示意圖|LeetCode 242

本文完整拆解 LeetCode 242 Valid Anagram 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Valid Anagram 一次弄懂。

Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link


Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

 

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

 

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Python

				
					# class Solution(object):
#     def isAnagram(self, s, t):
#         return sorted(s) == sorted(t)

class Solution(object):
    def isAnagram(self, s, t):
        return  collections.Counter(s) == collections.Counter(t)
				
			

Valid Anagram 解題思路

判斷兩字串是否為字母重組,本質是比較「每個字元出現幾次」。既然只關心次數而不關心順序,就用計數表取代排序:第一個字串加一、第二個字串減一,最後只要所有計數都歸零就是 anagram。

Valid Anagram 演算法步驟

  1. 先比較長度,長度不同可以直接回傳 false。
  2. 建立一個計數表(英文小寫可用長度 26 的陣列,Unicode 則用雜湊表)。
  3. 走訪第一個字串,每個字元計數加一;走訪第二個字串,每個字元計數減一。
  4. 檢查計數表是否全為 0,是則回傳 true。

Valid Anagram 複雜度分析

項目複雜度
時間複雜度O(n)
空間複雜度O(1)

兩趟線性掃描加一次固定長度的檢查,時間為 O(n)。若限定英文小寫,計數表大小固定為 26,空間視為 O(1);若要支援完整 Unicode,空間會變成 O(字元種類數)。

Valid Anagram 的邊界情況與常見錯誤

  • 長度不同時提早回傳可以省掉整趟計數。
  • 空字串與空字串互為 anagram,應回傳 true。
  • 大小寫是否視為相同要看題目定義,本題預設區分。
  • 遇到中文或 emoji 等多位元字元時,用陣列索引會出錯,必須改用雜湊表。

Valid Anagram 其他解法比較

解法時間空間說明
兩個字串都排序後比對O(n log n)O(n)寫法最短,但會多花排序時間
雜湊表計數O(n)O(k)可支援任意字元集
固定長度計數陣列O(n)O(1)本文採用,常數最小