Skip to content

Commit 1609183

Browse files
authored
Create the-k-th-lexicographical-string-of-all-happy-strings-of-length-n.cpp
1 parent 0954447 commit 1609183

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
string getHappyString(int n, int k) {
7+
auto base = 1 << (n - 1);
8+
if (k > 3 * base) {
9+
return "";
10+
}
11+
string result = string(1, 'a' + (k - 1) / base);
12+
while (base > 1) {
13+
k -= ((k - 1) / base) * base;
14+
base >>= 1;
15+
result += (k - 1) / base == 0
16+
? (result.back() != 'a' ? 'a' : 'b')
17+
: (result.back() != 'c' ? 'c' : 'b');
18+
}
19+
return result;
20+
}
21+
};

0 commit comments

Comments
 (0)