鱼C论坛

 找回密码
 立即注册
查看: 1399|回复: 0

[技术交流] C++刷LeetCode(1405. 最长快乐字符串)【贪心思想】

[复制链接]
发表于 2020-7-21 12:28:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
题目描述:
  1. 如果字符串中不含有任何 'aaa','bbb' 或 'ccc' 这样的字符串作为子串,那么该字符串就是一个「快乐字符串」。

  2. 给你三个整数 a,b ,c,请你返回 任意一个 满足下列全部条件的字符串 s:

  3. s 是一个尽可能长的快乐字符串。
  4. s 中 最多 有a 个字母 'a'、b 个字母 'b'、c 个字母 'c' 。
  5. s 中只含有 'a'、'b' 、'c' 三种字母。
  6. 如果不存在这样的字符串 s ,请返回一个空字符串 ""。

  7.  

  8. 示例 1:

  9. 输入:a = 1, b = 1, c = 7
  10. 输出:"ccaccbcc"
  11. 解释:"ccbccacc" 也是一种正确答案。
  12. 示例 2:

  13. 输入:a = 2, b = 2, c = 1
  14. 输出:"aabbc"
  15. 示例 3:

  16. 输入:a = 7, b = 1, c = 0
  17. 输出:"aabaa"
  18. 解释:这是该测试用例的唯一正确答案。
  19.  

  20. 提示:

  21. 0 <= a, b, c <= 100
  22. a + b + c > 0

  23. 来源:力扣(LeetCode)
  24. 链接:https://leetcode-cn.com/problems/longest-happy-string
  25. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码


  1. class Solution {
  2. public:
  3.     bool valid(string& res, int pos, string temp){
  4.         string store = res;
  5.         store.insert(pos, temp);
  6.         for(int i = 0; i < store.size() - 2; i++){
  7.             if(store[i] == temp[0] && store[i+1] == temp[0] && store[i+2] == temp[0])return false;
  8.         }
  9.         return true;
  10.     }
  11.     string longestDiverseString(int a, int b, int c) {
  12.         string res;
  13.         vector<pair<int, string> > store;
  14.         store.push_back(make_pair(a, "a"));
  15.         store.push_back(make_pair(b, "b"));
  16.         store.push_back(make_pair(c, "c"));
  17.         sort(store.begin(), store.end());
  18.         string temp1 = "abc";
  19.         int count1 = store[0].first;
  20.         for(int i = 0; i < count1; i++)res += temp1;
  21.         string temp2 = store[1].second + store[2].second;
  22.         int count2 = store[1].first - store[0].first;
  23.         for(int i = 0; i < count2; i++)res += temp2;
  24.         string temp3 = store[2].second;
  25.         int count3 = store[2].first - store[1].first;
  26.         for(int i = 0; i < count3; i++){
  27.             bool flag = false;
  28.             for(int j = 0; j <= res.size(); j++){
  29.                 if(valid(res, j, temp3)){
  30.                     res.insert(j, temp3);
  31.                     flag = true;
  32.                     break;
  33.                 }
  34.             }
  35.             if(flag == false)break;
  36.         }
  37.         return res;
  38.     }
  39. };
复制代码


参考链接:https://leetcode-cn.com/problems ... a-ru-by-time-limit/

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 20:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表