public class Solution {
    public bool IsAnagram(string s, string t) {
        Dictionary<char, int> dic = new Dictionary<char, int>();
            foreach (var c in s)
            {
                if (!dic.ContainsKey(c))
                {
                    dic.Add(c, 1);
                }
                else
                {
                    dic[c]++;
                }
            }

            foreach (var c in t)
            {
                if (!dic.ContainsKey(c))
                {
                    return false;
                }
                else
                {
                    dic[c]--;
                }
            }

            foreach (var d in dic)
            {
                if (d.Value != 0)
                {
                    return false;
                }
            }

            return true;
    }
}

https://leetcode.com/problems/valid-anagram/#/description

 

补充一个python的实现:

 1 class Solution:
 2     def isAnagram(self, s: str, t: str) -> bool:
 3         c1 = collections.Counter(s)
 4         c2 = collections.Counter(t)
 5         if len(c1) != len(c2):
 6             return False
 7         for k,v in c1.items():
 8             if k not in c2 or v != c2[k]:
 9                 return False
10         return True

 

posted on 2017-04-19 11:20  Sempron2800+  阅读(188)  评论(0编辑  收藏  举报