payal-kothari
9/8/2017 - 8:26 PM

Valid Anangram leetcode

//////////////// Solution 1
class Solution {
    public boolean isAnagram(String s, String t) {
        HashMap<Character,Integer> map = new HashMap<>();
        
        for(char c: s.toCharArray()){
            int freq = map.getOrDefault(c,0);      // ******
            map.put(c, ++freq);
        }
        
        for(char c : t.toCharArray()){
            if(map.get(c) != null){
                int freq = map.get(c);
                map.put(c, --freq);
            }else{
                return false;
            }
        }
        
        // for(Character c : map.keySet()){             // to iterate over keys   ----  map.keySet() 
        //     System.out.println("Key = " + c);
        // }
        
        for(Integer v : map.values()){                  // to iterate over values ---- map.values()
            if(v != 0)
                return false;
        }
        return true;
    } 
}




////////////////////   Solution 2

   public class Solution {
    public boolean isAnagram(String s, String t) {
        int[] freq = new int[26];
        for (int i = 0; i < s.length(); i++) {
            freq[s.charAt(i) - 'a']++;
        }
        for (int i = 0; i < t.length(); i++) {
            freq[t.charAt(i) - 'a']--;
        }
            
        for (int i : freq) {
            if (i != 0){
                return false;
            }
        }
            
        return true;
     }
  }