Skip to content

Commit 5fb999c

Browse files
authored
Create The k-th Lexicographical String of All Happy Strings of Length n.java
1 parent 04175b6 commit 5fb999c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
private static final char[] CHARS = {'a', 'b', 'c'};
3+
4+
public String getHappyString(int n, int k) {
5+
Set<String> set = new HashSet<>();
6+
backtrack(set, new StringBuilder(), n);
7+
if (set.size() < k) {
8+
return "";
9+
}
10+
List<String> list = new ArrayList<>(set);
11+
Collections.sort(list);
12+
return list.get(k - 1);
13+
}
14+
15+
private void backtrack(Set<String> set, StringBuilder sb, int n) {
16+
if (sb.length() == n) {
17+
set.add(sb.toString());
18+
return;
19+
}
20+
for (char c : CHARS) {
21+
if (sb.isEmpty() || sb.charAt(sb.length() - 1) != c) {
22+
sb.append(c);
23+
backtrack(set, sb, n);
24+
sb.deleteCharAt(sb.length() - 1);
25+
}
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)