<p>Given a string <code>s</code>, rearrange the characters of <code>s</code> so that any two adjacent characters are not the same.</p>

<p>Return <em>any possible rearrangement of</em> <code>s</code> <em>or return</em> <code>&quot;&quot;</code> <em>if not possible</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> "aba"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "aaab"
<strong>Output:</strong> ""
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 500</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    bool dfs(int id, int target, char prev, string &tmp, string &res, vector<int> &char_cnt) {
        if (id == target) {
            res = tmp;
            return true;
        } else {
            for (int i = 0; i < 26; i++) {
                if (char_cnt[i] > 0) {
                    if (id == 0 || ((prev - 'a') != i)) {
                        char_cnt[i] -= 1;
                        tmp[id] = 'a' + i;
                        bool flag = dfs(id+1, target, tmp[id], tmp, res, char_cnt);
                        char_cnt[i] += 1;
                        if (flag) {
                            return true;
                        }
                    }
                } 
            }
            return false;
        }
    }

    struct cmp {
        bool operator() (const pair<int, int> &l, const pair<int, int> &r) {
            return l.second < r.second;
        }
    };

    void helper(priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> &pq,
                char &prev,
                string &tmp) {
        auto item = pq.top();
        pq.pop();
        prev = item.first + 'a';
        if (item.second > 1) {
            pq.push({item.first, item.second - 1});
        }
    }
    string reorganizeString(string s) {
        vector<int> char_cnt(26, 0);
        for (auto c: s) {
            char_cnt[c - 'a'] += 1;
        } 
        string tmp = s;
        priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;

        for (int i = 0; i < char_cnt.size(); i++) {
            if (char_cnt[i] > 0){
                pq.push({i, char_cnt[i]});
            }
        }
        int id = 0;
        char prev = ' ';
        
        for (int id = 0; id < s.size(); id++) {
            if (id == 0 || pq.top().first != (prev - 'a')) {
                helper(pq, prev, tmp);
                tmp[id] = prev;

            } else {
                auto item1 = pq.top();
                pq.pop();
                if (pq.size() == 0) {
                    return "";
                } else {
                    helper(pq, prev, tmp);
                    tmp[id] = prev;

                }
                pq.push(item1);
            }
        }

        // Start the dfs search
        return tmp;
    }
};
9400