leetcode1405 最长快乐字符串


思路:

贪心。

实现:

 1 class Solution
 2 {
 3 public:
 4     bool check(string s, char c)
 5     {
 6         int n = s.length();
 7         if (n < 2) return false;
 8         if (s[n - 1] == s[n - 2] and s[n - 1] == c) return true;
 9         return false;
10     }
11     string longestDiverseString(int a, int b, int c)
12     {
13         string res = "";
14         priority_queueint, char>> q;
15         if (a) q.push({a, 'a'});
16         if (b) q.push({b, 'b'});
17         if (c) q.push({c, 'c'});
18         while (!q.empty())
19         {
20             auto tmp = q.top(); q.pop();
21             int m = tmp.first; char ch = tmp.second;
22             bool flg = false;
23             if (check(res, ch))
24             {
25                 if (q.empty()) break;
26                 else
27                 {
28                     auto tmp2 = q.top(); q.pop();
29                     m = tmp2.first; ch = tmp2.second;
30                     flg = true;
31                 }
32             }
33             m--; res += ch;
34             if (m) q.push({m, ch});
35             if (flg) q.push(tmp);
36         }
37         return res;
38     }
39 };