题意得:s串中不能出现"aaa",“bbb”,“ccc"意思说最多只能连续插入2个字符。可以先一个一个的插入,则其左右必不相同。
贪心思想: 优先选择插入最多的,比如第一个样例,第一次插入结果则应该为"cacbc”;最后再遍历,将剩余的字符添进去。得”ccaccbcc“;
class Solution {
public String longestDiverseString(int a, int b, int c) {
//序号
Integer[] ind = new Integer[4];
// 个数
int[] cnt = new int[4];
cnt[1] = a; cnt[2] = b; cnt[3] = c;
ind[1] = 1;ind[2] = 2; ind[3] = 3;
// 将插入的序号放入 数组中
List<Integer> list = new ArrayList<>();
list.add(0);
boolean flag = true;
while(flag){
//排序, 确保每次优先选择最多的插入
Arrays.sort(ind,1,4,(x,y) -> cnt[y] - cnt[x]);
flag = false;
int temp = list.get(list.size() - 1);
for(int i = 1; i <= 3 && flag == false; i++){
//当插入的字符与 前一个不同时,并且 还有剩余则插入
if(temp != ind[i] && cnt[ind[i]] > 0){
list.add(ind[i]);
flag = true;
cnt[ind[i]]--;
}
}
}
StringBuilder ans = new StringBuilder();
for(int i = 1; i < list.size(); i++){
int temp = list.get(i);
ans.append(ichar(temp));
//当前还可以添加时,添加。
if(cnt[temp] > 0){
ans.append(ichar(temp));
cnt[temp] --;
}
}
return ans.toString();
}
// 整型转字符
private static char ichar(int x){
if(x == 1)return 'a';
if(x == 2)return 'b';
return 'c';
}
}
代码参考 B站大神,wnjxyk(坑神);