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.
if a string comes repeatedly, you have to increase its counter value,
for repeative string:
for repeating only once: add 1 to counter
for repeating twice: add 2 to counter
.... and so on.
Set subStrCount = new HashSet<>();
Map existingStringCount = new HashMap<>();
int countAnagram = 0;
int subStrLen=1;
while (subStrLen != s.length()){
for (int i=0; i+subStrLen<=s.length(); i++) {
char tempArray[] = s.substring(i,i+subStrLen).toCharArray();
Arrays.sort(tempArray);
String sortedSubString = new String(tempArray);
if(subStrCount.contains(sortedSubString)) {
if(!existingStringCount.containsKey(sortedSubString)) {
countAnagram++;
existingStringCount.put(sortedSubString, 1);
}
else {
existingStringCount.put(sortedSubString, existingStringCount.get(sortedSubString)+1);
countAnagram += existingStringCount.get(sortedSubString);
}
}
subStrCount.add(sortedSubString);
}
subStrLen++;
}
return countAnagram;
}
subStrLen++;
}
return countAnagram;
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 →
if a string comes repeatedly, you have to increase its counter value, for repeative string: for repeating only once: add 1 to counter for repeating twice: add 2 to counter .... and so on.