力扣-1405-最长快乐字符串
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; } };
本文作者:Ryomk
本文链接:https://www.cnblogs.com/preccrep/p/15867670.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步