首页 > 其他 > 详细

[LeetCode] Valid Anagram

时间:2017-07-16 22:19:53      阅读:313      评论:0      收藏:0      [点我收藏+]

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

 

[LeetCode] Valid Anagram

原文:http://www.cnblogs.com/immjc/p/7192079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!