LeetCode 767. 重构字符串(堆)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 767. 重构字符串(堆)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
給定一個字符串S,檢查是否能重新排布其中的字母,使得兩相鄰的字符不同。
若可行,輸出任意可行的結果。若不可行,返回空字符串。
示例 1: 輸入: S = "aab" 輸出: "aba"示例 2: 輸入: S = "aaab" 輸出: ""注意: S 只包含小寫字母并且長度在[1, 500]區間內。來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/reorganize-string
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
參考 LeetCode 358. K 距離間隔重排字符串(貪心+優先隊列),一模一樣,K=2本題
struct cmp { bool operator()(pair<char,int>& a, pair<char,int>& b){return a.second < b.second;//數量多的優先} }; class Solution { public:string reorganizeString(string S) {int maxcount = 0;vector<int> count(26, 0);for(char c : S){count[c-'a']++;maxcount = max(maxcount, count[c-'a']);}if(maxcount > (S.size()+1)/2)return "";priority_queue<pair<char,int>, vector<pair<char,int>>, cmp> q;for(int i = 0; i < 26; ++i){if(count[i]>0)q.push({'a'+i, count[i]});}string ans;while(q.size() >= 2){vector<pair<char,int>> tmp;int dis = 2;while(dis--){auto tp = q.top();q.pop();char c = tp.first;int num = tp.second;ans += c;num--;if(num > 0)tmp.push_back({c, num});}for(auto& p : tmp)q.push(p);}while(!q.empty()){if(q.top().second == 1){ans += q.top().first;q.pop();}elsereturn "";}return ans;} };4 ms 6.3 MB
本題還可以:
- 字符計數,按頻數排序,大的先放
- 奇偶位置插空放置即可
0 ms 6.2 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 767. 重构字符串(堆)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 第 35 场双周赛(2
- 下一篇: LeetCode 963. 最小面积矩形