Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit5fb999c

Browse files
authored
Create The k-th Lexicographical String of All Happy Strings of Length n.java
1 parent04175b6 commit5fb999c

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+
classSolution {
2+
privatestaticfinalchar[]CHARS = {'a','b','c'};
3+
4+
publicStringgetHappyString(intn,intk) {
5+
Set<String>set =newHashSet<>();
6+
backtrack(set,newStringBuilder(),n);
7+
if (set.size() <k) {
8+
return"";
9+
}
10+
List<String>list =newArrayList<>(set);
11+
Collections.sort(list);
12+
returnlist.get(k -1);
13+
}
14+
15+
privatevoidbacktrack(Set<String>set,StringBuildersb,intn) {
16+
if (sb.length() ==n) {
17+
set.add(sb.toString());
18+
return;
19+
}
20+
for (charc :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)

[8]ページ先頭

©2009-2025 Movatter.jp