[LeetCode] 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.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

使用一个map存储s中字母及其出现的次数,通过map查找t中元素是否出现,如果出现则让它在m中的出现次数-1,如果没有出现,则返回false。最后判断map中的值是否全部为0,如果是则证明两个字符串是有效的,否则返回false。

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> m;
        for (char c : s)
            m[c]++;
        for (int i = 0; i != t.size(); i++) {
            if (m.count(t[i]))
                m[t[i]]--;
            else
                return false;
        }
        for (auto it = m.begin(); it != m.end(); it++) {
            if (it->second != 0)
                return false;
        }
        return true;
    }
};
// 19 ms

 也可以先对两个字符串进行排序,比较排序后的字符串,如果相同返回true,如果不同返回false。

class Solution {
public:
    bool isAnagram(string s, string t) {
        sort(s.begin(), s.end());
        sort(t.begin(), t.end());
        if (s == t)
            return true;
        else
            return false;
    }
};
// 23 ms

 

posted @ 2017-07-16 21:55  immjc  阅读(124)  评论(0编辑  收藏  举报