• ㊗️
• 大家
• offer
• 多多！

Problem

Given a string s and an integer k, rearrange s such that the same characters are at least distance k from each other. If it is not possible to rearrange the string, return an empty string “”.

Example 1:

Input: s = "aabbcc", k = 3
Output: "abcabc"
Explanation: The same letters are at least a distance of 3 from each other.


Example 2:

Input: s = "aaabc", k = 3
Output: ""
Explanation: It is not possible to rearrange the string.


Example 3:

Input: s = "aaadbbcc", k = 2
Output: "abacabcd"
Explanation: The same letters are at least a distance of 2 from each other.


Code

class Solution {
public String rearrangeString(String s, int k) {
if(s == null || s.length() == 1) return s;

int[] dict = new int[26];
int[] valid = new int[26];

for(char c : s.toCharArray()){
dict[c - 'a']++;
}

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++){
int nextLetter = findNext(dict, valid, i);
if(nextLetter == -1){
return "";
}

sb.append((char)('a' + nextLetter));
dict[nextLetter]--;
valid[nextLetter] = i + k;
}

return sb.toString();
}

private int findNext(int[] dict, int[] valid, int index){
int res = -1;
int max = 0;
for(int i = 0; i < 26; i++){
if(max < dict[i] && valid[i] <= index){
res = i;
max = dict[i];
}
}

return res;
}
}