leetcode1415. The k-th Lexicographical String of All Happy Strings of Length n
不飞则已,一飞冲天;不鸣则已,一鸣惊人。这篇文章主要讲述leetcode1415. The k-th Lexicographical String of All Happy Strings of Length n相关的知识,希望能为你提供帮助。
【leetcode1415. The k-th Lexicographical String of All Happy Strings of Length n】题目如下:
A happy string is a string that:解题思路:n和k都很小,最简单的方法是把所有符合条件的string都求出来,排序后可得到结果。
For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings.
- consists only of letters of the set
[‘a‘, ‘b‘, ‘c‘]
.s[i] != s[i + 1]
for all values ofi
from1
tos.length - 1
(string is 1-indexed).
Given two integersn
andk
, consider a list of all happy strings of lengthn
sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less thank
happy strings of lengthn
.
Example 1:
Input: n = 1, k = 3 Output: "c" Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c".
Example 2:
Input: n = 1, k = 4 Output: "" Explanation: There are only 3 happy strings of length 1.
Example 3:
Input: n = 3, k = 9 Output: "cab" Explanation: There are 12 different happy string of length 3 ["aba", "abc", "aca", "acb", "bab", "bac", "bca", "bcb", "cab",
"cac", "cba", "cbc"]. You will find the 9th string = "cab"
Example 4:
Input: n = 2, k = 7 Output: ""
Example 5:
Input: n = 10, k = 100 Output: "abacbabacb"
Constraints:
1 < = n < = 10
1 < = k < = 100
代码如下:
class Solution(object): def getHappyString(self, n, k): """ :type n: int :type k: int :rtype: str """ queue = [‘a‘,‘b‘,‘c‘]l = [] while len(queue) > 0: item = queue.pop(0) if len(item) == n: l.append(item) continue if item[-1] == ‘a‘: queue.append(item + ‘b‘) queue.append(item + ‘c‘) elif item[-1] == ‘b‘: queue.append(item + ‘a‘) queue.append(item + ‘c‘) elif item[-1] == ‘c‘: queue.append(item + ‘a‘) queue.append(item + ‘b‘)l.sort() if len(l) < k: return ‘‘ return l[k-1]
推荐阅读
- LeetCode 202. 快乐数 Happy Number
- uni-app canvas 实现文字居中
- 精华!Oracle面试题和答案全集
- 不容错过的Neo4J面试题和答案推荐
- 史上最全的MySQL面试题和答案大汇总
- MongoDB面试题和答案全集解析
- Java面试(JOGL面试题和答案合集)
- jBPM面试题和答案详细图解
- Java调试(JDB面试题和答案合集)