[LeetCode-Short Answer Question] 242. Valid allophones

topic

Insert image description here

Method 1: Array storage:

class Solution {
    
    
    public boolean isAnagram(String s, String t) {
    
    
        int[] s1 = new int[26];
        int[] t1 = new int[26];
        for(int  i =0; i< s.length() ; i++)
            s1[s.charAt(i)-'a']++;

         for(int  i =0; i< t.length() ; i++)
            t1[t.charAt(i)-'a']++;

        return Arrays.equals(s1,t1);
    }
}

Method 2: Hash storage

class Solution {
    
    
    public boolean isAnagram(String s, String t) {
    
    
        if(s.length() != t.length()) return false;
     Map<Character,Integer> map = new HashMap<>();
     for(char s1 : s.toCharArray()){
    
    
         if(!map.containsKey(s1)) map.put(s1,1);
         else map.put(s1,map.get(s1)+1);
     }
      for(char t1 : t.toCharArray()){
    
    
         if(!map.containsKey(t1)) continue;
         if(map.get(t1) == 1) map.remove(t1);
         else if(map.get(t1) > 1) map.put(t1,map.get(t1)-1);
     }

     return map.size()==0;
       
    }
}

Guess you like

Origin blog.csdn.net/weixin_45618869/article/details/132847156