leetcode 1405. 最長快樂字符串

1405. 最長快樂字符串
如果字符串中不含有任何 ‘aaa’,‘bbb’ 或 ‘ccc’ 這樣的字符串作爲子串,那麼該字符串就是一個「快樂字符串」。

給你三個整數 a,b ,c,請你返回 任意一個 滿足下列全部條件的字符串 s:

s 是一個儘可能長的快樂字符串。
s 中 最多 有a 個字母 ‘a’、b 個字母 ‘b’、c 個字母 ‘c’ 。
s 中只含有 ‘a’、‘b’ 、‘c’ 三種字母。
如果不存在這樣的字符串 s ,請返回一個空字符串 “”。

示例 1:

輸入:a = 1, b = 1, c = 7
輸出:“ccaccbcc”
解釋:“ccbccacc” 也是一種正確答案。
示例 2:

輸入:a = 2, b = 2, c = 1
輸出:“aabbc”
示例 3:

輸入:a = 7, b = 1, c = 0
輸出:“aabaa”
解釋:這是該測試用例的唯一正確答案。

提示:

0 <= a, b, c <= 100
a + b + c > 0

來源:力扣(LeetCode)


思路分析

這個最長快樂字符串,做起來一點都不快樂,想哭/(ㄒoㄒ)/~~,哪位大佬看到指點一下。
最後實在想不出來了,只AC了24/33組。
這個存在問題的思路先記錄下來:

  1. 採用map存儲a,b,c三個字符與他們的數目之間的關係數組;
  2. 然後採用優先隊列實現每次先考慮的是字符數目最多的字符;
  3. 每次加入生成string中後,就將該類型字符先存儲在臨時pair類型裏面;
  4. 等到下一個字符插入生成字符串後,再將此時臨時pair類型放入優先隊列,簡單來說,就是每次間隔一次,在考慮一次。

代碼解析

class Solution {
public:
    string longestDiverseString(int a, int b, int c) {
        string s;
        map<string, int> cur;
        pair<int, string> ted1, ted2;
        int x = a, y = b, z = c;
        cur["a"] = a;
        cur["b"] = b;
        cur["c"] = c;
        priority_queue<pair<int,string> > hed;
        for (auto it = cur.begin(); it != cur.end(); it++) 
            hed.push(make_pair(it->second,it->first));
        while (hed.size() > 0){
            if (hed.top().first >= 2) {
                s += hed.top().second;
                s += hed.top().second;
                if (ted1.first != 0 && ted1.second != hed.top().second)
                    hed.push(ted1);
                ted1 = hed.top();
                ted1.first -= 2;//數量減少2
                hed.pop();
            }
            else{
                s += hed.top().second;
                hed.pop();
                hed.push(ted1);
            }
        }
        return s;
    }
};

未實現以下功能
在這裏插入圖片描述

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