forked from anishLearnsToCode/leetcode-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveLetterToEqualizeFrequency.java
52 lines (43 loc) · 1.87 KB
/
RemoveLetterToEqualizeFrequency.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
// https://leetcode.com/problems/remove-letter-to-equalize-frequency
// T: O(|word|)
// S: O(1)
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class RemoveLetterToEqualizeFrequency {
public boolean equalFrequency(String word) {
final Map<Character, Integer> letterFrequency = getFrequencies(word);
final Map<Integer, Integer> numberFrequency = getFrequencies(letterFrequency.values());
if (letterFrequency.size() == 1) {
return true;
}
if (numberFrequency.size() == 1 && numberFrequency.keySet().iterator().next() == 1) {
return true;
}
if (numberFrequency.size() == 1 || numberFrequency.size() > 2) {
return false;
}
final Iterator<Integer> iterator = numberFrequency.keySet().iterator();
final int first = iterator.next(), second = iterator.next();
final int smallerNum = Math.min(first, second);
final int largerNum = Math.max(first, second);
final int smallerNumFreq = numberFrequency.get(smallerNum);
final int largerNumFreq = numberFrequency.get(largerNum);
return ((largerNum - smallerNum == 1) && largerNumFreq == 1) || (smallerNum == 1 && smallerNumFreq == 1);
}
private Map<Character, Integer> getFrequencies(String string) {
final Map<Character, Integer> result = new HashMap<>();
for (int index = 0 ; index < string.length() ; index++) {
char letter = string.charAt(index);
result.put(letter, result.getOrDefault(letter, 0) + 1);
}
return result;
}
private Map<Integer, Integer> getFrequencies(Iterable<Integer> iterable) {
final Map<Integer, Integer> result = new HashMap<>();
for (int value : iterable) {
result.put(value, result.getOrDefault(value, 0) + 1);
}
return result;
}
}