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){intcount=0;Map<String,Integer>map=newHashMap<>();for(inti=0;i<s.length();i++){for(intj=i+1;j<=s.length();j++){Stringsubstring=s.substring(i,j);char[]chars=substring.toCharArray();Arrays.sort(chars);StringsortedSubstring=newString(chars);map.put(sortedSubstring,map.getOrDefault(sortedSubstring,0)+1);}}for(intvalue:map.values()){count+=value*(value-1)/2;// combination formula is n * (n - 1) / 2}returncount;}
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