[LeetCode] Valid Anagram 驗證變位詞


 

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;
    }
};

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM