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
Related Topics:
Backtracking
// OJ: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
// Author: github.com/lzl124631x
// Time: O(3^N)
// Space: O(1)
class Solution {
string addOne(string &s) {
int i = s.size() - 1;
for (; i >= 0; --i) {
if (s[i] == 'c') {
s[i] = 'a';
continue;
}
s[i]++;
break;
}
return i == -1 ? (s = "") : s;
}
bool valid(string &s) {
int i = s.size() - 1;
for (; i > 0; --i) {
if (s[i] == s[i - 1]) return false;
}
return true;
}
string next(string &s) {
do {
addOne(s);
} while (s != "" && !valid(s));
return s;
}
public:
string getHappyString(int n, int k) {
string ans;
for (int i = 0; i < n; ++i) ans.push_back(i % 2 == 0 ? 'a' : 'b');
while (--k) {
ans = next(ans);
if (ans == "") return "";
}
return ans;
}
};
// OJ: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
// Author: github.com/lzl124631x
// Time: O(3^N). It should be smaller than O(3^N) since there are cases skipped earlier, but should be greater than O(NK).
// Space: O(NK)
// Ref: https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/discuss/585557/C%2B%2B-Straightforward-DFS.-Skip-appending-same-char.
class Solution {
vector<string> ans;
void dfs(string &cur, int n, int k) {
if (ans.size() == k) return;
if (cur.size() == n) {
ans.push_back(cur);
return;
}
for (int i = 0; i < 3; ++i) {
if (cur.size() && cur.back() == 'a' + i) continue;
cur.push_back('a' + i);
dfs(cur, n, k);
cur.pop_back();
}
}
public:
string getHappyString(int n, int k) {
string cur;
dfs(cur, n, k);
return ans.size() == k ? ans.back() : "";
}
};