LeetCode767. 重構字符串

767. Reorganize String

[Medium] Given a string S, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.

If possible, output any possible result. If not possible, return the empty string.

Example 1:

Input: S = "aab"
Output: "aba"

Example 2:

Input: S = "aaab"
Output: ""

Note:

  • S will consist of lowercase letters and have length in range [1, 500].

題目:給定一個字符串S,檢查是否能重新排布其中的字母,使得兩相鄰的字符不同。若可行,輸出任意可行的結果。若不可行,返回空字符串。

思路:按照字符的頻率構建優先隊列。每次優先考慮添加頻率最高的字符,如果衝突,則考慮添加頻率次高的字符。

工程代碼下載 Github

class Solution {
public:
    string reorganizeString(string S) {
        int arr[26] = {0};
        for(auto c : S)
            arr[c-'a'] += 1;

        priority_queue<pair<int, char>, vector<pair<int, char>>> pq;
        for(int i = 0; i < 26; ++i){
            if(arr[i] > (S.size()+1)/2)
                return "";
            if(arr[i] > 0)
                pq.push({arr[i], 'a'+i});
        }

        string res;
        while(!pq.empty()){
            pair<int, char> p1 = pq.top();
            pq.pop();

            if(res.empty() || res.back() != p1.second){
                res += p1.second;
                if(p1.first > 1)
                    pq.push({p1.first-1, p1.second});
            }
            else{
                // 如果隊列當前最高頻的字符 與 結果字符串的最後一個字符相同
                // 則考慮添加次高頻的字符
                if(pq.empty())
                    return "";
                pair<int, char> p2 = pq.top();
                pq.pop();
                res += p2.second;
                if(p2.first > 1)
                    pq.push({p2.first-1, p2.second});
                pq.push(p1);
            }
        }

        return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章