leetcode No.242 有效的字母异位词

//注意:当两个字符串相同的时候返回也是true
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length())
            return false;
        HashMap<Character,Integer> map=new HashMap<>();
        for(char c:s.toCharArray()){
            map.put(c,map.getOrDefault(c,0)+1);//这一行避免了用if else
        }
        for(char c:t.toCharArray()){    //不断减一这个做法比较巧妙
            if(map.get(c)==null)
                return false;
            int count=map.get(c);
            if(count>1)
                map.put(c,count-1);
            else
                map.remove(c);
        }
        return map.isEmpty();
    }
}

//另一种巧妙的解法,要比上面快很多
class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length()) 
            return false;
        int[] arrayS=new int[26];
        int[] arrayT=new int[26];
        for(char c:s.toCharArray()){
            arrayS[c-'a']++;
        }
        for(char c:t.toCharArray()){
            arrayT[c-'a']++;
        }
        for(int j=0;j<26;j++){
            if(arrayS[j]!=arrayT[j])
                return false;
        }
        return true;
    }
}

此外 还可以用排序去做

猜你喜欢

转载自blog.csdn.net/qq_33399567/article/details/89148324