-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathResult.java
More file actions
77 lines (61 loc) · 2.07 KB
/
Result.java
File metadata and controls
77 lines (61 loc) · 2.07 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package hackrank.algorithm.string.sherlock;
import java.util.HashMap;
import java.util.Map;
/**
* @see <a href="https://www.hackerrank.com/challenges/sherlock-and-valid-string">Sherlock and the Valid String</a>
*/
public class Result {
/**
* @param s lowercase letters in ASCII range a-z
* @return "YES" if {@code s} is a valid string, "NO"" otherwise.
*/
public static String isValid(String s) {
Map<Character, Integer> counts = countChars(s);
boolean valid = false;
if (hasEqualCounts(counts, '-')) {
// use '-' dummy char to check if original value is already valid and requires no fixing
valid = true;
} else {
// iterate over chars to see if decrementing their count by 1 equals out other counts
for (char character : counts.keySet()) {
if (hasEqualCounts(counts, character)) {
valid = true;
break;
}
}
}
return valid ? "YES" : "NO";
}
private static Map<Character, Integer> countChars(String value) {
Map<Character, Integer> counts = new HashMap<>();
for (char character : value.toCharArray()) {
if (!counts.containsKey(character)) {
counts.put(character, 0);
}
int count = counts.get(character);
count++;
counts.put(character, count);
}
return counts;
}
private static boolean hasEqualCounts(Map<Character, Integer> counts, char charToReduceByOne) {
int firstCount = -1;
for (char character : counts.keySet()) {
int count = counts.get(character);
if (character == charToReduceByOne) {
count--;
}
if (count <= 0) {
continue;
}
if (firstCount == -1) {
firstCount = count;
continue;
}
if (firstCount != count) {
return false;
}
}
return true;
}
}