标签: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; } } }
标签:string sort uil alt else res std code public
原文地址:https://www.cnblogs.com/oldby/p/12638538.html