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.
This is my Java solution, see if it will help you understand it better. Any feedback will be greatly appreciated.
staticintsherlockAndAnagrams(Strings){intn=s.length();//This will control the length of each substring each pass.//For the first pass, it will 1(every single character), next 2, every 2 blocks of characters etc..intI=1;intnumOfAnagrams=0;//Looping through n - 1 (number of substrings).//2nd loop, looks at each substring for each length.//3rd loop loops through the rest of the substrings of the same length as s1.for(inti=0;i<n-1;i++){for(intj=0;j<=n-I;j++){Strings1=s.substring(j,j+I);for(intk=j+1;k<=n-I;k++){Strings2=s.substring(k,k+I);if(checkAnagrams(s1,s2))numOfAnagrams++;}}I++;}returnnumOfAnagrams;}staticbooleancheckAnagrams(Strings1,Strings2){//Creating 2 HashMaps to hold each char of strings and their frequncies, then checking if they are equal or not. If they are equal, they are anagrams.Map<Character,Integer>s1Map=newHashMap<>();Map<Character,Integer>s2Map=newHashMap<>();char[]s1Chars=s1.toCharArray();char[]s2Chars=s2.toCharArray();//s1 and s2 will be coming in as the same length.for(inti=0;i<s1.length();i++){Characters1Char=Character.valueOf(s1Chars[i]);Characters2Char=Character.valueOf(s2Chars[i]);if(s1Map.containsKey(s1Char))s1Map.put(s1Char,s1Map.get(s1Char)+1);elses1Map.put(s1Char,1);if(s2Map.containsKey(s2Char))s2Map.put(s2Char,s2Map.get(s2Char)+1);elses2Map.put(s2Char,1);}returns1Map.equals(s2Map);}
Sherlock and Anagrams
You are viewing a single comment's thread. Return to all comments →
This is my Java solution, see if it will help you understand it better. Any feedback will be greatly appreciated.