-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathResult.java
More file actions
51 lines (43 loc) · 1.76 KB
/
Result.java
File metadata and controls
51 lines (43 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package hackrank.algorithm.string.shergram;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @see <a href="https://www.hackerrank.com/challenges/sherlock-and-anagrams">Sherlock and Anagrams</a>
*/
public class Result {
/**
* @param s value to look for substrings of anagrammatic pairs
* @return number of unordered anagrammatic pairs of substrings in {@code s}
*/
public static int sherlockAndAnagrams(String s) {
int count = 0;
for (int substringLength = 1; substringLength < s.length(); substringLength++) {
List<String> substrings = findSubstrings(s, substringLength);
for (int i = 0; i < substrings.size(); i++) {
for (int j = i + 1; j < substrings.size(); j++) {
if (substrings.get(i).equals(substrings.get(j))) {
count++;
}
}
}
}
return count;
}
private static List<String> findSubstrings(String value, int length) {
int numberSubstrings = value.length() - length + 1;
return IntStream.range(0, numberSubstrings).mapToObj(i -> {
char[] charsSubstring = getSubstring(value, i, length);
Arrays.sort(charsSubstring); // sort to "normalize" anagrams. allows for a simple string equals comparison
return new String(charsSubstring);
}).collect(Collectors.toList());
}
private static char[] getSubstring(String value, int startIndex, int length) {
char[] substring = new char[length];
for (int i = startIndex, j = 0; i < startIndex + length; i++, j++) {
substring[j] = value.charAt(i);
}
return substring;
}
}