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.
static int sherlockAndAnagrams(String s) {
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
for (int j = i + 1; j < s.length() + 1; j++) {
char[] chars = s.substring(i,j).toCharArray();
Arrays.sort(chars);
set.add(new String(chars));
int val = 1;
// How many substring exists
if(map.get(String.valueOf(chars)) != null) val = map.get(String.valueOf(chars)) + 1;
map.put(String.valueOf(chars), val);
}
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if(entry.getValue() > 1) {
// Find how many different pairs the string has (start from n - 1 to find all the pairs)
result += ((entry.getValue() - 1) * entry.getValue())/2;
}
}
// System.out.println(map);
return result;
}
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 →
My Java Solution(I had to use HashMap):