力扣-1405-最长快乐字符串

题目链接
按照这个思路
我自己的AC代码:

class Solution {
    class node{
    public:
        int x,y;
        node(int x,int y){
            this->x=x;
            this->y=y;
        }
        friend bool operator<(const node&n1,const node&n2){
            return n1.y<n2.y;
        }
    };
public:
    string longestDiverseString(int a, int b, int c) {
        priority_queue<node>q;
        if(a) q.push(node(0,a));
        if(b) q.push(node(1,b));
        if(c) q.push(node(2,c));
        string ans="";
        int n=0;
        while(!q.empty()){
            auto [x,y]=q.top();
            q.pop();
            if(n>=2&&ans[n-1]==(char)(x+'a')&&ans[n-2]==(char)(x+'a')){
                if(q.empty()) break;
                auto [x1,y1]=q.top();
                q.pop();
                ans+=(char)(x1+'a');
                ++n;
                if(--y1) q.push(node(x1,y1));
                q.push(node(x,y));
            }else{
                ans+=(char)(x+'a');
                ++n;
                if(--y) q.push(node(x,y));
            }
        }
        return ans;
    }
};

在评论区看到的另外一种可以学习的写法:

class Solution {
    #define x first
    #define y second
    typedef pair<int, int> PII;
public:
    string longestDiverseString(int a, int b, int c) {
        priority_queue<PII> heap;
        if (a) heap.push({a, 0});
        if (b) heap.push({b, 1});
        if (c) heap.push({c, 2});
        string ans;
        while (heap.size()) {
            PII t = heap.top();
            heap.pop();
            int n = ans.size();
            if (n >= 2 && ans[n - 1] - 'a' == t.y && ans[n - 2] - 'a' == t.y) {
                if (heap.empty()) break;
                PII t1 = heap.top(); heap.pop();
                ans += t1.y + 'a';
                if (t1.x - 1 > 0) heap.push({t1.x - 1, t1.y});
                heap.push(t);
            } else {
                ans += t.y + 'a';
                if (t.x - 1 > 0) heap.push({t.x - 1, t.y});
            }
        }
        return ans;
    }
};
posted @ 2022-02-07 13:59  Ryomk  阅读(25)  评论(0编辑  收藏  举报