LeetCode Valid Anagram

242. Valid Anagram 242. Valid Anagram

Given two strings s and , 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? 242. Valid Anagram


“Anagram”这个词的意思是“易位构词游戏”,就是把一个word中的letter打乱。本题要判断两个字符串是否是anagram。简单题,直接对两个字符串hash,分别统计出现字符的频率,如果两个hash的结果完全一样,则是anagram;否则不是。 这题和LeetCode Word Pattern类似,也是要保证两个字符串hash到的频率完全一样,即是一个双射。完整代码如下:

class Solution {
public:
    bool isAnagram(string s, string t)
    {
        unordered_map<char, int> ums, umt;
        for (int i = 0; i < s.size(); ++i) {
            ++ums[s[i]];
        }
        for (int i = 0; i < t.size(); ++i) {
            ++umt[t[i]];
        }
        unordered_map<char, int>::iterator it = ums.begin();
        while (it != ums.end()) {
            if (umt[it->first] != it->second)
                return false;
            ++it;
        }
        it = umt.begin();
        while (it != umt.end()) {
            if (ums[it->first] != it->second)
                return false;
            ++it;
        }
        return true;
    }
};

本代码提交AC,用时16MS。
还有一种方法就是对两个字符串都排个序,然后判等,代码很简单,但是排序复杂度要比直接hash稍高。代码如下:

class Solution {
public:
    bool isAnagram(string s, string t)
    {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        return s == t;
    }
};

本代码提交AC,用时26MS。

Leave a Reply

Your email address will not be published. Required fields are marked *