题目大意:
现在我们有a个'a', b个'b' , c个'c'. 问我们怎么组合这些字符使得这个字符串尽可能长,而且不存在连续3个相同的字符。找出这个字符串。
a,b,c<=100
解题思路:
因为a,b,c<= 100 其实是可以用dp来做的。不过需要用dp来打印路径。先讲一下dp怎么做吧。其实就是无脑5维dp即可。
dp[a][b][c][d][e]. 表示 当前我们还有a个'a', b个'b' , c个'c', 前一个字母是d+‘a’ ,且前一个字母已经重复e个时候最长的字符串的个数。选的时候注意不要让相同的字符出现3次。另外在打印路径时,其实也是在模拟dp的转移而已。
https://leetcode-cn.com/submissions/detail/59965037/
另外一种思路就稍微难想一点,其实我们每次都选出最多的字母出来即可。但是假如最多的字母已经有2个了,我们选次多的,假如次多的空了,我们就退出即可。
class Solution {
public:
string longestDiverseString(int a, int b, int c) {
stack<pair<int,char>> sta;
priority_queue<pair<int,char> , vector<pair<int,char>> , less<pair<int,char>> > pq;
pq.push({a,'a'});
pq.push({b,'b'});
pq.push({c,'c'});
string ret;
while(pq.top().first > 0 ){
pair<int,char > tmp = pq.top();
pq.pop();
if(ret.size()>=2 && ret.back() == tmp.second && ret[ret.size()-2] == tmp.second ){
sta.push(tmp);
tmp = pq.top();
pq.pop();
if(tmp.first == 0)break;
tmp.first -- ;
sta.push(tmp);
ret+=tmp.second;
}else{
tmp.first -- ;
ret+=tmp.second;
sta.push(tmp);
}
while(sta.size()){
tmp = sta.top();
sta.pop();
pq.push(tmp);
}
}
return ret;
}
};