Java/242. Valid Anagram 有效的字母异位词

题目

Java/242. Valid Anagram 有效的字母异位词


Java/242. Valid Anagram 有效的字母异位词

 

 

 

代码部分一(6ms 71.86%)

class Solution {
    public boolean isAnagram(String s, String t) {
        int n1 = s.length();
        int n2 = t.length();
        if(n1 != n2)return false;
        
        int count = 0;
        boolean res = true;
        int[] firstCount = new int[26];
        int[] secondCount = new int[26];
        
        for(int i = 0; i < n1; i++){
            firstCount[s.charAt(i) - 'a']++;
        }
        
        for(int i = 0; i < n2; i++){
            secondCount[(int)t.charAt(i) - 'a']++;
        }
        
        for(int i = 0; i < 26; i++){
            if(firstCount[i] != secondCount[i]) count++;
            if(count > 1){
                res = false;
                break;
            }
            
        }
        
        return res;
    }
}