242. Valid Anagram (E)

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?


我的答案:hash table (multiset慢好幾倍)

class Solution {
public:
    bool isAnagram(string s, string t) {
        int len_s = s.size();
        int len_t = t.size();
        if (len_s != len_t)
            return false;
        
        unordered_map<char, int> map_s;
        unordered_map<char, int> map_t;
        
        for (int i=0; i<len_s; ++i) {
            char c_s = s[i];
            char c_t = t[i];
            
            if (map_s.find(c_s) == map_s.end())
                map_s[c_s] = 1;
            else
                ++map_s[c_s];
            
            if (map_t.find(c_t) == map_t.end())
                map_t[c_t] = 1;
            else
                ++map_t[c_t];
        }
        
        for (const auto& p_s : map_s) {
            if ( p_s.second != map_t[p_s.first] ) {
                return false;
            }
        }
        
        return true;
    }
};

Runtime: 28 ms, faster than 44.13% of C++ online submissions for Valid Anagram.
Memory Usage: 7.7 MB, less than 22.42% of C++ online submissions for Valid Anagram.

看答案:
https://leetcode.com/problems/valid-anagram/solution/
確實用hash table比較快,但是這邊不用2個hash table,只用一個,然后加減就可以了,想到229這道題
https://leetcode.com/problems/majority-element-ii/discuss/63520/Boyer-Moore-Majority-Vote-algorithm-and-my-elaboration
Boyer-Moore Majority Vote algorithm

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Remove time complexity: remove from a set is O(1), remove...
    云端漫步_b5aa閱讀 726評論 0 0
  • https://leetcode.com/problems/valid-anagram/description/解...
    becauseyou_90cd閱讀 161評論 0 0
  • 算法思想貪心思想雙指針排序快速選擇堆排序桶排序荷蘭國旗問題二分查找搜索BFSDFSBacktracking分治動態(tài)...
    第六象限閱讀 4,889評論 0 0
  • 問題: 給定一個n元素數(shù)組,求出現(xiàn)次數(shù)最大的元素(即Majority Element),并且數(shù)組保證該元素出現(xiàn)的次...
    gattonero閱讀 1,044評論 0 0
  • 漸變的面目拼圖要我怎么拼? 我是疲乏了還是投降了? 不是不允許自己墜落, 我沒有滴水不進(jìn)的保護(hù)膜。 就是害怕變得面...
    悶熱當(dāng)乘涼閱讀 4,463評論 0 13

友情鏈接更多精彩內(nèi)容