leetcode-华为专题-767. 重构字符串
用到hash表+堆
class Solution { public: string reorganizeString(string s) { map<char, int> maps; // 对于偶数n而言,如果出现最多字母个数超过n/2,则肯定有两相邻元素相同。 // 对于奇数而言,如果出现最多字母个数超过(n+1)/2,则肯定有两相邻元素相同。 // 因此可以统一,无论奇数还是偶数,如果出现最多字母个数超过(n+1)/2,则肯定有两相邻元素相同。 string res; for(auto str:s){ maps[str]++; if(maps[str]>(s.size()+1)/2) // 如果频次大于(n+1)/2,直接返回空 return res; } priority_queue<pair<int,char>> q; // 默认按照频次从大到小 // 按照频次在前,字母在后入对 for(auto mp:maps){ q.push({mp.second, mp.first}); } while(q.size()>1){ // 每次取两个,所以 >1 // 每次按照频次取最前面两个,这俩个字母肯定不同 char temp1 = q.top().second; q.pop(); char temp2 = q.top().second; q.pop(); //cout<<"temp1: "<<temp1<<" temp2: "<<temp2<<endl; res = res + temp1; res = res + temp2; // 再将这两个字母次数减1 maps[temp1]--; maps[temp2]--; // 如果减去后的频次仍大于1,再次入队 if(maps[temp1]>0) q.push({maps[temp1],temp1}); if(maps[temp2]>0) q.push({maps[temp2],temp2}); } // 因为每次取两个元素,如果总的个数是奇数,肯定还剩一个,最后加上 if(q.size()>0) res = res + q.top().second; return res; } };