leetcode1405. 最长快乐字符串(贪心算法)

如果字符串中不含有任何 ‘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” 也是一种正确答案。

代码

class Solution {
    public String longestDiverseString(int a, int b, int c) {

        int[] helper=new int[]{a,b,c};
        StringBuilder stringBuilder=new StringBuilder();
        int pre=-1,dou=-1;
        ArrayList<Character> list=new ArrayList<>();
        while (true)
        {
            int max=-1,maxN=-1;
            for(int i=0;i<3;i++)//找出当前最多的字母
            {
                if(helper[i]==0||i==dou) continue;//已经选两次或没有了余量就不能选了
                if(helper[i]>=maxN)
                {
                    max=i;
                    maxN=helper[i];
                }
          
            }
            if(max==-1) break;//找不到了就退出
            helper[max]--;
            if(pre==max)//和上一个字母相同,下次循环就不能再选了
            {
                dou=max;
            }else{
                dou=-1;
            }
            stringBuilder.append((char)(max+'a'));
            pre=max;
        }
      return stringBuilder.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值