-
Notifications
You must be signed in to change notification settings - Fork 1
/
RemoveLetterToEqualizeFrequency.java
48 lines (42 loc) · 1.16 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
package com.smlnskgmail.jaman.leetcodejava.easy;
// https://leetcode.com/problems/remove-letter-to-equalize-frequency/
public class RemoveLetterToEqualizeFrequency {
private final String input;
public RemoveLetterToEqualizeFrequency(String input) {
this.input = input;
}
public boolean solution() {
int[] freq = new int[26];
for (int i = 0; i < input.length(); i++) {
freq[input.charAt(i) - 'a']++;
}
for (char c = 'a'; c <= 'z'; c++) {
int i = c - 'a';
if (freq[i] > 0) {
freq[i]--;
if (allSame(freq)) {
return true;
}
freq[i]++;
}
}
return false;
}
private boolean allSame(int[] freq) {
int same = 0;
int i = 0;
for (int f : freq) {
if (f > 0) {
same = f;
break;
}
}
for (int j = i + 1; j < freq.length; j++) {
int curr = freq[j];
if (curr > 0 && curr != same) {
return false;
}
}
return true;
}
}