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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Remove time complexity: remove from a set is O(1), remove...
    云端漫步_b5aa阅读 667评论 0 0
  • Problem Given an array of size n, find the majority eleme...
    朔方烟尘阅读 312评论 0 0
  • https://leetcode.com/problems/valid-anagram/description/解...
    becauseyou_90cd阅读 139评论 0 0
  • 算法思想贪心思想双指针排序快速选择堆排序桶排序荷兰国旗问题二分查找搜索BFSDFSBacktracking分治动态...
    第六象限阅读 3,272评论 0 0
  • 问题: 给定一个n元素数组,求出现次数最大的元素(即Majority Element),并且数组保证该元素出现的次...
    gattonero阅读 1,010评论 0 0