class Solution {
public String longestDiverseString(int a, int b, int c) {
StringBuilder sb = new StringBuilder();
ArrayList<RedefineType> list = new ArrayList<>();
list.add(new RedefineType('a',a));
list.add(new RedefineType('b',b));
list.add(new RedefineType('c',c));
int count = 0;
Iterator<RedefineType> it = list.iterator();
for (RedefineType type : list) {
it.next();
count=count+type.num;
}
//对三个字符的个数从大到小排序,然后每次选2个剩余最多的字符存入string中,如果与上次选择的重复了,则选次多的存入string。如此循环。
while( count>0 ){
Collections.sort(list,(o1, o2) -> o2.num-o1.num );//降序排序,后面这个参数为空或者o1-o2都是自然排序,即升序
if(sb.length()>0 && list.get(0).name== sb.charAt(sb.length()-1)){
if(list.get(1).num!=0){
sb.append(list.get(1).name);
count--;
list.get(1).num--;
}else{
return sb.toString();
}
}else{
if(list.get(0).num!=0) {
sb.append(list.get(0).name);
count--;
list.get(0).num--;
}
if(list.get(0).num!=0) {
sb.append(list.get(0).name);
count--;
list.get(0).num--;
}
}
}
return sb.toString();
}
static class RedefineType{
public char name;
public int num;
public RedefineType(char name,int num){
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "RedefineType{" +
"name=" + name +
", num=" + num +
'}';
}
}
}
参考博文:
贪心—leetcode1405最长快乐字符串