We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java15 solution that passes all test cases. Three HashMaps and a dream...
publicstaticintmakeAnagram(Stringa,Stringb){intcount=0;HashMap<Character,Integer>aCharFreq=newHashMap<Character,Integer>();HashMap<Character,Integer>bCharFreq=newHashMap<Character,Integer>();HashMap<Character,Integer>toDelCharFreq=newHashMap<Character,Integer>();for(inti=0;i<a.length();i++){//Get the character frequencies for string a.charc=a.charAt(i);if(aCharFreq.containsKey(c))aCharFreq.replace(c,aCharFreq.get(c)+1);elseaCharFreq.put(c,1);}for(inti=0;i<b.length();i++){//Get the character frequencies for string b.chard=b.charAt(i);if(bCharFreq.containsKey(d))bCharFreq.replace(d,bCharFreq.get(d)+1);elsebCharFreq.put(d,1);}for(charkeyA:aCharFreq.keySet()){//Now check the character frequencies for string a.if(bCharFreq.containsKey(keyA))toDelCharFreq.put(keyA,Math.abs(bCharFreq.get(keyA)-aCharFreq.get(keyA)));//If b contains the character in a that we're looking at, add the difference between the number of times that character shows up in b and a.elsetoDelCharFreq.put(keyA,aCharFreq.get(keyA));//Add every character that shows up in a but not b.}for(charkeyB:bCharFreq.keySet()){//Then check the character frequencies for string b.if(aCharFreq.containsKey(keyB)&&toDelCharFreq.get(keyB)==0)toDelCharFreq.remove(keyB);//If a and b have an equal number of instances of a character, that character will be part of the anagram set and must be removed from the target character frequencies.elseif(!aCharFreq.containsKey(keyB))toDelCharFreq.put(keyB,bCharFreq.get(keyB));//Add every character that shows up in b but not a.}for(charkey:toDelCharFreq.keySet())count+=toDelCharFreq.get(key);//Finally, add up the frequencies of all characters remaining to get the retur value.returncount;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Strings: Making Anagrams
You are viewing a single comment's thread. Return to all comments →
Java15 solution that passes all test cases. Three HashMaps and a dream...