LeetCode 1405. 最长快乐字符串 (贪心)

最长快乐字符串
由于在三个字符的数量都差不多的时候,能组成的字符串最长。
所以采取这样的贪心策略:

  • 优先选取数量多的字符
  • 如果不能,选次多的。
  • 如果还不能,选最少的。
  • 如果没有了,结束循环。
class Solution {
    
    
public:
    string longestDiverseString(int a, int b, int c) {
    
    
        char v[] = {
    
    'a','b','c'};
        int cnt[] = {
    
    a,b,c};
        string ans = "";   
        while(true){
    
    
            int size = ans.size();
            int p1 = 0 , p2 = -1;
            for(int i=1;i<3;i++){
    
    
                if(cnt[i]>cnt[p1]){
    
    
                    p2 = p1;
                    p1 = i;
                }else if(p2 == -1 || cnt[i]>cnt[p2]){
    
    
                    p2 = i;
                }
            }
            if(cnt[p1]==0) break;
            
            if(size>=2 && ans[size-1]==v[p1] && ans[size-2]==v[p1]){
    
    
                if(cnt[p2]==0) break;
                ans.push_back(v[p2]);
                cnt[p2]--;
            }else{
    
    
                ans.push_back(v[p1]);
                cnt[p1]--;
            }
        }
        return ans;
    }
};
// a >= b > = c  
// (b+c+1)*2 >= a

猜你喜欢

转载自blog.csdn.net/qq_44846324/article/details/109007067