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.
publicstaticintsherlockAndAnagrams(Strings){Map<String,Integer>occurrences=newHashMap<>();for(inti=0;i<s.length();i++){for(intj=i;j<s.length();j++){Stringval=sortString(s.substring(i,j+1));occurrences.put(val,occurrences.getOrDefault(val,0)+1);}}intanagramPairCount=0;occurrences=removeSingleOccurrences(occurrences);for(Map.Entry<String,Integer>e:occurrences.entrySet()){// Once occurrence ‘o’ of each frequency array is stored, total anagrams will be the sum of// o*(o-1)/2 for all different frequency arrays because if a particular substring has ‘o’ anagrams in// string total o*(o-1)/2 anagram pairs can be formed. Below is the implementation of above idea.// The division by two is needed to disregard different combinations between two elements:// [0, 1] and [1, 0]anagramPairCount+=(e.getValue()*(e.getValue()-1))/2;}returnanagramPairCount;}privatestaticMap<String,Integer>removeSingleOccurrences(Map<String,Integer>occurrences){returnoccurrences.entrySet().stream().filter(e->e.getValue()>1).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));}privatestaticStringsortString(Stringstr){char[]charArray=str.toCharArray();Arrays.sort(charArray);returnString.valueOf(charArray);}
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 →
Java