leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0767.cpp (887B)


      1 class Solution {
      2     typedef pair<int, char> pic;
      3 
      4   public:
      5     string reorganizeString(const string &s) {
      6         priority_queue<pic> pq;
      7         int count[27] = {0};
      8         string res;
      9 
     10         for (char c : s)
     11             count[c & 0x1F]++;
     12         for (int i = 1; i <= 26; i++)
     13             if (count[i] > 0) pq.push({count[i], 'a' + i - 1});
     14 
     15         while (!pq.empty()) {
     16             const auto [cnt, c] = pq.top();
     17             pq.pop();
     18             if (pq.empty()) {
     19                 if (cnt == 1)
     20                     return res + c;
     21                 else
     22                     return "";
     23             } else {
     24                 const auto [ocnt, oc] = pq.top();
     25                 pq.pop();
     26                 res += c, res += oc;
     27                 if (cnt - 1) pq.push({cnt - 1, c});
     28                 if (ocnt - 1) pq.push({ocnt - 1, oc});
     29             }
     30         }
     31         return res;
     32     }
     33 };