Advertisement
nikunjsoni

767

May 25th, 2021
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string reorganizeString(string s) {
  4.         int freq[26]={0};
  5.         for(char ch: s)
  6.             freq[ch-'a']++;
  7.        
  8.         priority_queue<pair<int, int>> pq;
  9.         for(int i=0; i<26; i++)
  10.             if(freq[i])
  11.                 pq.push({freq[i], i});
  12.        
  13.         string ans = "";
  14.         while(pq.size() > 1){
  15.             auto num1 = pq.top(); pq.pop();
  16.             auto num2 = pq.top(); pq.pop();
  17.             num1.first--; num2.first--;
  18.             if(num1.first)  pq.push(num1);
  19.             if(num2.first)  pq.push(num2);
  20.             ans += 'a'+num1.second;
  21.             ans += 'a'+num2.second;
  22.         }
  23.        
  24.         if(!pq.size() || (pq.size() == 1 && pq.top().first == 1)){
  25.             if(pq.size())
  26.                 ans += (pq.top().second + 'a');
  27.             return ans;
  28.         }
  29.         return "";
  30.     }
  31. };
  32.  
  33. -------------------------------
  34.  
  35. class Solution {
  36. public:
  37.     string reorganizeString(string S) {
  38.         vector<int> cnt(26);
  39.         int mostFreq = 0, i = 0;
  40.  
  41.         for(char c : S)
  42.             if(++cnt[c - 'a'] > cnt[mostFreq])
  43.                 mostFreq = (c - 'a');
  44.  
  45.         if(2 * cnt[mostFreq] - 1 > S.size()) return "";
  46.  
  47.         while(cnt[mostFreq]) {
  48.             S[i] = ('a' + mostFreq);
  49.             i += 2;
  50.             cnt[mostFreq]--;
  51.         }
  52.  
  53.         for(int j = 0; j < 26; j++) {
  54.             while(cnt[j]) {
  55.                 if(i >= S.size()) i = 1;
  56.                 S[i] = ('a' + j);
  57.                 cnt[j]--;
  58.                 i += 2;
  59.             }
  60.         }
  61.  
  62.         return S;
  63.     }
  64. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement