码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-5195-最长快乐字符串

时间:2020-04-05 20:22:22      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:string   sort   uil   alt   else   res   std   code   public   

题目描述:

技术图片

 

 第一次提交 python:

class Solution:
    def longestDiverseString(self, a: int, b: int, c: int) -> str:
        res = ""
        l = [["a", a], ["b", b], ["c", c]]
        l.sort(key = lambda x: x[1],reverse=True)
        while l[0][1] > 0:
            if len(res) < 2 or res[-2] != l[0][0] or res[-1] != l[0][0]:
                res += l[0][0]
                l[0][1] -= 1
            else:
                if l[1][1] <= 0:
                    return res
                res += l[1][0]
                l[1][1] -= 1
            l.sort(key=lambda x: x[1], reverse=True)
            if l[0][1] == 0:
                return res
        return res

java

class Solution {
    public String longestDiverseString(int a, int b, int c) {
        MyChar [] myChars = new MyChar[]{
            new MyChar(a,a),
            new MyChar(b,b),
            new MyChar(c,c),
        };
        StringBuilder sb = new StringBuilder();
        while(true){
            Arrays.sort(myChars);
            if(sb.length() >= 2 &&
                sb.charAt(sb.length() - 1) == myChars[2].ch &&
                sb.charAt(sb.length() - 2) == myChars[2].ch){
                if(myChars[1].count-- >0){
                    sb.append(myChars[1].ch);
                }else{
                    break;
                }
            }else{
                if(myChars[2].count-- > 0){
                    sb.append(myChars[2].ch);
                }else{
                    break;
                }
            }
        }
        return sb.toString();
    }
   private class MyChar implements Comparable{
        char ch;
        int count;
        public MyChar(char ch,int count){
            this.ch = ch;
            this.count = count;
        }
        @Override
        public int compareTo(Object o){
            MyChar other = (MyChar) o;
            return this.count - other.count;
        }
    }
}

 

leetcode-5195-最长快乐字符串

标签:string   sort   uil   alt   else   res   std   code   public   

原文地址:https://www.cnblogs.com/oldby/p/12638538.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!