一个小算法题的对比

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.


class Solution { public: bool isAnagram(string s, string t) { if (s.length() != t.length()) return false; int n = s.length(); unordered_map<char, int> counts; for (int i = 0; i < n; i++) { counts[s[i]]++; counts[t[i]]--; }//直接引用key值hash到second的值未做到一步 for (auto count : counts)////新的foreach 用法 if (count.second) return false; return true; } };
/////////////////////////////////
class Solution {
public:
    bool isAnagram(string s, string t) {
        if(s.size()!=t.size())
        {
            return false;
        }
        if(s.size()==0)return true;
        unordered_map<char,int> h;
        for(int a=0;a<s.size();a++)
        {
            h[s[a]]++;
        }
        for(int b=0;b<t.size();b++)
        {
         if(h.find(t[b])==h.end())return false;
         h.find(t[b])->second--;
        }
        for(auto start=h.begin();start!=h.end();start++)
        {
            if(start->second!=0)return false;
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/fenglongyu/p/7572257.html