leetcode 242. 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.

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

很常見的題目,可以以空間換時間

class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.length() != t.length())
            return 0;
        int exist[30] = {0};
        for(int i = 0; i < s.length(); i++)
            exist[s[i]-'a']++;
        for(int i = 0; i < t.length(); i++){
            if(--exist[t[i]-'a'] < 0)
                return 0;
        }
        return 1;
    }
};

至於如果是unicode的話,可以用C++的unordered_map(底層以hash實現)來做。

另附:leetcode上的題解

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章