-
Notifications
You must be signed in to change notification settings - Fork 5
/
SpecialStringAgain.java
67 lines (58 loc) · 2.25 KB
/
SpecialStringAgain.java
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// https://www.hackerrank.com/challenges/special-palindrome-again/problem
package string;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class SpecialStringAgain {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int length = scanner.nextInt();
String string = scanner.next();
System.out.println(specialStrings(string));
}
static long specialStrings(String string) {
long count = 0;
for (int index = 0 ; index < string.length() ; index++) {
Distribution distribution = new Distribution();
for (int j = index ; j < string.length() ; j++) {
distribution.add(string.charAt(j));
if ((j - index + 1) % 2 == 0) {
count += distribution.frequencies.size() == 1 ? 1 : 0;
} else {
count += distribution.frequencies.size() <= 2
&& distribution.histogramCounter() < 2
&& string.charAt(index + (j - index + 1) / 2) == distribution.charWithSmallestFrequency()
? 1 : 0 ;
}
if (distribution.frequencies.size() > 2 || distribution.histogramCounter() > 1) {
break;
}
}
}
return count;
}
private static class Distribution {
private final Map<Character, Integer> frequencies = new HashMap<>();
void add(char character) {
frequencies.put(character, frequencies.getOrDefault(character, 0) + 1);
}
char charWithSmallestFrequency() {
int minFrequency = frequencies.values().stream().min(Integer::compareTo).get();
for (Map.Entry<Character, Integer> entry : frequencies.entrySet()) {
if (entry.getValue() == minFrequency) {
return entry.getKey();
}
}
return '*';
}
int histogramCounter() {
int count = 0;
for (Map.Entry<Character, Integer> entry : frequencies.entrySet()) {
if (entry.getValue() > 1) {
count++;
}
}
return count;
}
}
}