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.
I literally had almost this exact code except for one little thing that made it error...totalCount = totalCount + value. I was thinking that you would add one each time you found a matching string, so my code used totalCount++ instead. Can anyone explain why adding the values of the map works?
Also, here's my identical (working) Java code for those who are interested.
staticintsherlockAndAnagrams(Strings){// go through a string and add every value to a hashmapHashMap<String,Integer>map=newHashMap<>();// total of anagramsinttotal=0;// for each key, add one to valuefor(inti=0;i<s.length();i++){for(intj=i+1;j<=s.length();j++){// get substring and sort it!Stringsub=s.substring(i,j);// sorting the stringchartempArray[]=sub.toCharArray();Arrays.sort(tempArray);sub=newString(tempArray);if(map.containsKey(sub)){// adds one to last valueintoldValue=map.get(sub);// total++ WRONGtotal+=oldValue;// RIGHTmap.put(sub,++oldValue);}else{// add to map if not seenmap.put(sub,1);}}}returntotal;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
I literally had almost this exact code except for one little thing that made it error...
totalCount = totalCount + value
. I was thinking that you would add one each time you found a matching string, so my code usedtotalCount++
instead. Can anyone explain why adding the values of the map works?Also, here's my identical (working) Java code for those who are interested.