leetcode-5195-最长快乐字符串
Posted 真不知道叫啥好
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-5195-最长快乐字符串相关的知识,希望对你有一定的参考价值。
题目描述:
第一次提交 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-最长快乐字符串的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 1405 最长快乐字符串[贪心] HERODING的LeetCode之路