ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2022-02-07 14:02:00  阅读:177  来源: 互联网

标签:node int t1 力扣 push heap ans 字符串 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;
    }
};

标签:node,int,t1,力扣,push,heap,ans,字符串,1405
来源: https://www.cnblogs.com/preccrep/p/15867670.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有