題意得: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(坑神);