leetcode 242. 有效的字母异位词 Valid Anagram(使用c++/java/python)【使用哈希表】

针对两个字符串分别建立哈希表,key为字母,value为字母出现的次数。 若两个哈希表完全相同,则字符串互为字母异位词。

执行用时: c++ 12ms; java 28ms; python 64ms

 

c++

class Solution {
public:
    bool isAnagram(string s, string t) {
        unordered_map<char, int> smap, tmap;
        for (auto c:s) smap[c]++;
        for (auto c:t) tmap[c]++;
        return smap == tmap; 
    }
};

 

java

class Solution {
    public boolean isAnagram(String s, String t) {
        Map<Character,Integer> smap = new HashMap();
        Map<Character,Integer> tmap = new HashMap();
        for(int i=0;i<s.length();i++)
        {
            char c = s.charAt(i);
            if(!smap.containsKey(c))
                smap.put(c,1);
            else
                smap.put(c,smap.get(c)+1);
        }
        for(int i=0;i<t.length();i++)
        {
            char c = t.charAt(i);
            if(!tmap.containsKey(c))
                tmap.put(c,1);
            else
                tmap.put(c,tmap.get(c)+1);
        }
        return smap.equals(tmap);
    }
}

 

python

class Solution:
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        smap = {}
        tmap = {}
        for c in s:
            if c not in smap:
                smap[c]=1
            else:
                smap[c]+=1
        for c in t:
            if c not in tmap:
                tmap[c]=1
            else:
                tmap[c]+=1
        return smap==tmap

 

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 18:25
点赞 评论 收藏
分享
_mos_:我以为手抄报简历就已经很顶了,没想到还有表格简历
点赞 评论 收藏
分享
06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务