-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSherlockAndTheValidString.java
74 lines (64 loc) · 2.59 KB
/
SherlockAndTheValidString.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
68
69
70
71
72
73
74
// https://www.hackerrank.com/challenges/sherlock-and-valid-string/problem
package strings;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class SherlockAndTheValidString {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.next();
System.out.println(isValidString(string) ? "YES" : "NO");
}
private static boolean isValidString(String string) {
Map<Character, Integer> frequencies = frequencies(string);
Map<Integer, Integer> distribution = frequencies(frequencies);
return distribution.size() <= 2
&& greaterThanSignleton(distribution) <= 1
&& (distribution.size() == 1 || singleElementCanBeRemoved(distribution));
}
private static boolean singleElementCanBeRemoved(Map<Integer, Integer> distribution) {
int removalFrequency = removal(distribution);
int retention = retention(distribution);
return removalFrequency - 1 == 0 || removalFrequency - 1 == retention;
}
private static int removal(Map<Integer, Integer> distribution) {
for (Map.Entry<Integer, Integer> entry : distribution.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return Integer.MAX_VALUE;
}
private static int retention(Map<Integer, Integer> distribution) {
for (Map.Entry<Integer, Integer> entry : distribution.entrySet()) {
if (entry.getValue() != 1) {
return entry.getKey();
}
}
return Integer.MAX_VALUE;
}
private static Map<Character, Integer> frequencies(String string) {
Map<Character, Integer> frequencies = new HashMap<>();
for (int index = 0 ; index < string.length() ; index++) {
char character = string.charAt(index);
frequencies.put(character, frequencies.getOrDefault(character, 0) + 1);
}
return frequencies;
}
private static Map<Integer, Integer> frequencies(Map<Character, Integer> map) {
Map<Integer, Integer> frequencies = new HashMap<>();
for (int frequency : map.values()) {
frequencies.put(frequency, frequencies.getOrDefault(frequency, 0) + 1);
}
return frequencies;
}
private static int greaterThanSignleton(Map<Integer, Integer> distribution) {
int counter = 0;
for (int frequency : distribution.values()) {
if (frequency > 1) {
counter++;
}
}
return counter;
}
}