Advertisement
nikunjsoni

358

Jun 22nd, 2021
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.75 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     string rearrangeString(string s, int k) {
  4.         int cnt[26] = {};
  5.         priority_queue<pair<int, int>> pq;
  6.         queue<pair<int, int>> q;
  7.         for (auto ch : s)
  8.             ++cnt[ch - 'a'];
  9.         for (auto i = 0; i < 26; ++i)
  10.             if (cnt[i] != 0)
  11.                 pq.push({cnt[i], i});
  12.         string res = "";
  13.         while (!pq.empty()) {
  14.             auto p = pq.top(); pq.pop();
  15.             res += 'a' + p.second;
  16.             q.push({p.first - 1, p.second});
  17.             if (q.size() >= k) {
  18.                 auto p = q.front(); q.pop();
  19.                 if (p.first)
  20.                     pq.push({p.first, p.second});
  21.             }
  22.         }
  23.         return res.size() == s.size() ? res : "";
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement