|
1 | 1 | package g1401_1500.s1415_the_k_th_lexicographical_string_of_all_happy_strings_of_length_n; |
2 | 2 |
|
3 | | -// #Medium #String #Backtracking #2022_03_26_Time_2_ms_(89.96%)_Space_40.8_MB_(91.57%) |
| 3 | +// #Medium #String #Backtracking #2022_03_27_Time_2_ms_(90.55%)_Space_42.5_MB_(65.75%) |
4 | 4 |
|
5 | 5 | public class Solution { |
6 | | - public String getHappyString(int n, int k) { |
7 | | - int finalLength = (int) (3 * Math.pow(2, n - 1)); |
8 | | - StringBuilder res = new StringBuilder(); |
9 | | - if (k > finalLength) { |
10 | | - return ""; |
| 6 | + private char[] arr = new char[] {'a', 'b', 'c'}; |
| 7 | + private String res = ""; |
| 8 | + private int k; |
| 9 | + |
| 10 | + private void get(StringBuilder str, int n, int index) { |
| 11 | + if (k < 1) { |
| 12 | + return; |
| 13 | + } |
| 14 | + if (str.length() == n) { |
| 15 | + if (k == 1) { |
| 16 | + res = str.toString(); |
| 17 | + } |
| 18 | + k--; |
| 19 | + return; |
11 | 20 | } |
12 | | - k--; |
13 | | - int previousCall = -1; |
14 | | - int calls = 3; |
15 | | - for (int i = 0; i < n; i++) { |
16 | | - int parts = finalLength / calls; |
17 | | - int currentCall = k / parts; |
18 | | - if (currentCall == 0) { |
19 | | - if (previousCall == 0) { |
20 | | - previousCall = 1; |
21 | | - } else { |
22 | | - previousCall = 0; |
23 | | - } |
24 | | - } else if (currentCall == 1) { |
25 | | - if (previousCall == -1 || previousCall == 2) { |
26 | | - previousCall = 1; |
27 | | - } else { |
28 | | - previousCall = 2; |
29 | | - } |
30 | | - } else { |
31 | | - previousCall = 2; |
| 21 | + for (int i = 0; i < 3; i++) { |
| 22 | + if (i == index) { |
| 23 | + continue; |
32 | 24 | } |
33 | | - calls = 2; |
34 | | - res.append((char) ('a' + previousCall)); |
35 | | - finalLength = parts; |
36 | | - k -= (currentCall * parts); |
| 25 | + str.append(arr[i]); |
| 26 | + get(str, n, i); |
| 27 | + str.deleteCharAt(str.length() - 1); |
37 | 28 | } |
38 | | - return res.toString(); |
| 29 | + } |
| 30 | + |
| 31 | + public String getHappyString(int n, int k) { |
| 32 | + this.k = k; |
| 33 | + get(new StringBuilder(), n, -1); |
| 34 | + return res; |
39 | 35 | } |
40 | 36 | } |
0 commit comments