题目描述:
如果字符串中不含有任何 ‘aaa’,‘bbb’ 或 ‘ccc’ 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。
给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:
s 是一个尽可能长的快乐字符串。
s 中 最多 有a 个字母 ‘a’、b 个字母 ‘b’、c 个字母 ‘c’ 。
s 中只含有 ‘a’、‘b’ 、‘c’ 三种字母。
如果不存在这样的字符串 s ,请返回一个空字符串 “”。
思路:
每次排序,把数量最多的排在前面,
每次最多可以放2个
如果当前字符串的最后一个元素与最多的字符相等的时候,则添加第二多的字符
代码如下:
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
string res="";
vector<vector<char>>pre;
pre.push_back({(char)a,'a'});
pre.push_back({(char)b,'b'});
pre.push_back({(char)c,'c'});
while(res.size()<a+b+c){
sort(pre.rbegin(),pre.rend());
if((res.size()>0)&&(res.back()==pre[0][1])){
if(pre[1][0]>0){
res.push_back(pre[1][1]);
pre[1][0]--;
}
else return res;
}
else{
if(pre[0][0]>0) {
res.push_back(pre[0][1]);
pre[0][0]--;
}
if(pre[0][0]>0) {
res.push_back(pre[0][1]);
pre[0][0]--;
}
}
}
return res;
}
};
python同样写法超时:
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
pre=[[a,'a'],[b,'b'],[c,'c']]
res=""
while len(res)<a+b+c:
if len(res)>0 and res[len(res)-1]==pre[0][1]:
if pre[1][0]>0:
res+=pre[1][1]
pre[1][0]-=1
else:
return res
else:
if pre[0][0]>0:
res+=pre[0][1]
pre[0][0]-=1
if pre[0][0]>0:
res+=pre[0][1]
pre[0][0]-=1
return res