-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRearrange-String-k-Distance-Apart.java
More file actions
38 lines (33 loc) · 1.18 KB
/
Copy pathRearrange-String-k-Distance-Apart.java
File metadata and controls
38 lines (33 loc) · 1.18 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
// 358. Rearrange String k Distance Apart
class Solution {
public String rearrangeString(String s, int k) {
int len = s.length();
int[] count = new int[26];
int[] valid = new int[26];
for (char c : s.toCharArray()) {
count[c - 'a']++;
}
StringBuilder sb = new StringBuilder();
// fill characters from 0 to end of string
for (int i = 0; i < len; i++) {
int candidateChar = findMaxLeft(count, valid, i);
if (candidateChar == -1) return "";
valid[candidateChar] = i + k;
count[candidateChar]--;
sb.append((char) ('a' + candidateChar));
}
return sb.toString();
}
public int findMaxLeft(int[] count, int[] valid, int index) {
int max = Integer.MIN_VALUE;
int candidateChar = -1;
// for each character check its left most position possible
for (int i = 0; i < count.length; i++) {
if (count[i] > 0 && index >= valid[i] && count[i] > max) {
max = count[i];
candidateChar = i;
}
}
return candidateChar;
}
}