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.

Solution:

bool isAnagram(string s, string t) {
    if(s.size() != t.size()) return false;
    unordered_map<char, int> map;
    for(auto c:s) map[c]++;
    for(auto c:t) {
        if(--map[c]<0) return false;
    }
    return true;
}

猜你喜欢

转载自yuanhsh.iteye.com/blog/2232581