class Solution { public boolean isAnagram(String s, String t) { if(s.length() != t.length()) return false; //traverse 1 string and make hashmap HashMap<Character,Integer> map = new HashMap<>(); for(int i = 0 ;i < s.length();i++){ char ch = s.charAt(i); map.put(ch , map.getOrDefault(ch,0)+1); } //now traverse 2nd string and keep removing for(int i =0 ;i < t.length();i++){ char ch = t.charAt(i); if(map.containsKey(ch)){ if(map.get(ch)==1) map.remove(ch); else map.put(ch,map.get(ch)-1); } else return false; } //if hashmap size is 0 they were valid anagram return true; } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter