程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode[1405] python3 implementation of the longest happy string (greedy method, dictionary sorting)

編輯:Python
# If the string does not contain any 'aaa','bbb' or 'ccc' Such a string is used as a substring , Then the string is a 「 Happy string 」. 
# 
# Here are three integers a,b ,c, Please return Any one A string that satisfies all of the following conditions s: 
# 
# 
# s Is a happy string as long as possible . 
# s in most Yes a Letters 'a'、b Letters 'b'、c Letters 'c' . 
# s It only contains 'a'、'b' 、'c' Three letters . 
# 
# 
# If such a string does not exist s , Please return an empty string "". 
# 
# 
# 
# Example 1: 
# 
# Input :a = 1, b = 1, c = 7
# Output :"ccaccbcc"
# explain :"ccbccacc" It is also a correct answer .
# 
# 
# Example 2: 
# 
# Input :a = 2, b = 2, c = 1
# Output :"aabbc"
# 
# 
# Example 3: 
# 
# Input :a = 7, b = 1, c = 0
# Output :"aabaa"
# explain : This is the only correct answer to the test case . 
# 
# 
# 
# Tips : 
# 
# 
# 0 <= a, b, c <= 100 
# a + b + c > 0 
# 
# Related Topics greedy character string Pile up ( Priority queue ) 123 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def longestDiverseString(self, a: int, b: int, c: int) -> str:
mm = {
'a':a, 'b':b, 'c':c}
ret = []
while True:
mm = dict(sorted(mm.items(), key=lambda kv: kv[1], reverse=True))
is_end = True
for k in mm.keys():
if (mm[k]==0 or (len(ret)>=2 and ret[-1]==k and ret[-2]==k)):
continue
ret.append(k)
mm[k] -= 1
is_end = False
break
if is_end: break
return "".join(ret)
# leetcode submit region end(Prohibit modification and deletion)

Take the letter that meets the conditions and has the largest number each time , If one round is not taken , End .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved