leetcode: 242. Valid Anagram

題目:

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

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

Input: s = "rat", t = "car"
Output: 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?

分析:題目很簡單。不過對 map 的使用瞭解更深了。
3 點收穫:

  1. map 中的元素初始默認值爲 0.
  2. 對 map 中元素遍歷,直接使用 auto就行(auto iter: h),而我是複雜的寫法。
  3. 因爲只有 26 個字母,使用數組代替 map 其實會更快。

貼一下我的代碼吧:

class Solution {
public:
    bool isAnagram(string s, string t) {
        map<char, int> h;
        for(char &c:s){
            h[c] += 1;
        }
        for(char &c:t){
            h[c] -= 1;
            
        }
        for(map<char, int>::iterator iter = h.begin(); iter != h.end(); ++iter){
            if(iter->second != 0){
                return 0;
            }
        }
        return 1;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章