Given two strings s and t, write a function to determine if t is an anagram of s.
For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.
Note:
You may assume the string contains only lowercase alphabets.
這不算一道難題,核心點就在於使用哈希表映射,我們還是用一個數組來代替哈希表,使用類似方法的題目有Minimum Window Substring 最小窗口子串,Isomorphic Strings 同構字符串,Longest Substring Without Repeating Characters 最長無重復子串 和 1.1 Unique Characters of a String 字符串中不同的字符。我們先判斷兩個字符串長度是否相同,不相同直接返回false。然后把s中所有的字符出現個數統計起來,存入一個大小為26的數組中,因為題目中限定了輸入字符串為小寫字母組成。然后我們再來統計t字符串,如果發現不匹配則返回false。 參見代碼如下:
class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) return false; int m[26] = {0}; for (int i = 0; i < s.size(); ++i) ++m[s[i] - 'a']; for (int i = 0; i < t.size(); ++i) { if (--m[t[i] - 'a'] < 0) return false; } return true; } };