public String rearrangeString(String s, int k) {
if (s == null || s.isEmpty() || k < 0) {
return "";
}
int[] count = new int[26];
int[] nextPos = new int[26];
// count occurrance of each char
for (int i = 0; i < s.length(); i++) {
int loc = s.charAt(i) - 'a';
count[loc]++;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
int validPos = getValidPos(count, nextPos, i);
if (validPos == -1) {
return "";
}
count[validPos]--;
nextPos[validPos] = i + k;
sb.append((char)('a' + validPos));
}
return sb.toString();
}
private int getValidPos(int[] count, int[] nextPos, int cur) {// 听说这个函数可以用priority queue来代替
int result = -1;
int max = Integer.MIN_VALUE;
for (int i = 0; i < 26; i++) {
if (count[i] > 0 && count[i] > max && cur >= nextPos[i]) {
result = i;
max = count[i];
}
}
return result;
}