A happy string is a string that:
- 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).
For example, strings “abc”, “ac”, “b” and “abcbabcbcb” are all happy strings and strings “aa”, “baa” and “ababbc” are not happy strings.
Given two integers n
and k
, consider a list of all happy strings of length n
sorted in lexicographical order.
Return the kth string of this list or return an empty string if there are less than k
happy strings of length n
.
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
Solution: DFS
Generate the happy strings in lexical order, store the k-th one.
Time complexity: O(n + k)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua class Solution { public: string getHappyString(int n, int k) { string ans; string cur; function<void()> dfs = [&]() { if (k <= 0) return; if (cur.length() == n) { if (--k == 0) ans = cur; return; } for (char ch = 'a'; ch <= 'c'; ++ch) { if (!cur.empty() && ch == cur.back()) continue; cur.push_back(ch); dfs(); cur.pop_back(); } }; dfs(); return k > 0 ? "" : ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment