|
| 1 | +package backtracking |
| 2 | + |
| 3 | +import "sort" |
| 4 | + |
| 5 | +/* |
| 6 | +A happy string is a string that: |
| 7 | +
|
| 8 | +consists only of letters of the set ['a', 'b', 'c']. |
| 9 | +s[i] != s[i + 1] for all values of i from 1 to s.length - 1 (string is 1-indexed). |
| 10 | +For example, strings "abc", "ac", "b" and "abcbabcbcb" are all happy strings and strings "aa", "baa" and "ababbc" are not happy strings. |
| 11 | +
|
| 12 | +Given two integers n and k, consider a list of all happy strings of length n sorted in lexicographical order. |
| 13 | +
|
| 14 | +Return the kth string of this list or return an empty string if there are less than k happy strings of length n. |
| 15 | +
|
| 16 | +
|
| 17 | +
|
| 18 | +Example 1: |
| 19 | +
|
| 20 | +Input: n = 1, k = 3 |
| 21 | +Output: "c" |
| 22 | +Explanation: The list ["a", "b", "c"] contains all happy strings of length 1. The third string is "c". |
| 23 | +*/ |
| 24 | + |
| 25 | +func getHappyString(n int, k int) string { |
| 26 | + happyStrings := getHappyStringUtil(0, n, "", []string{}) |
| 27 | + if len(happyStrings) < k { |
| 28 | + return "" |
| 29 | + } |
| 30 | + sort.Strings(happyStrings) |
| 31 | + return happyStrings[k-1] |
| 32 | +} |
| 33 | + |
| 34 | +func getHappyStringUtil(start, n int, result string, combinations []string) []string { |
| 35 | + if len(result) == n { |
| 36 | + combinations = append(combinations, result) |
| 37 | + return combinations |
| 38 | + } |
| 39 | + |
| 40 | + for _, ch := range []string{"a", "b", "c"} { |
| 41 | + if start > 0 && string(result[start-1]) == ch { |
| 42 | + continue |
| 43 | + } |
| 44 | + combinations = getHappyStringUtil(start+1, n, result+ch, combinations) |
| 45 | + } |
| 46 | + |
| 47 | + return combinations |
| 48 | +} |
| 49 | + |
| 50 | +func getHappyString1(n int, k int) string { |
| 51 | + count := 0 |
| 52 | + result := "" |
| 53 | + generateHappyString(0, n, "", k, &count, &result) |
| 54 | + return result |
| 55 | +} |
| 56 | + |
| 57 | +func generateHappyString(start, n int, current string, k int, count *int, result *string) { |
| 58 | + if len(current) == n { |
| 59 | + *count++ |
| 60 | + if *count == k { |
| 61 | + *result = current |
| 62 | + } |
| 63 | + return |
| 64 | + } |
| 65 | + |
| 66 | + for _, ch := range []byte{'a', 'b', 'c'} { |
| 67 | + if start > 0 && current[start-1] == ch { |
| 68 | + continue |
| 69 | + } |
| 70 | + generateHappyString(start+1, n, current+string(ch), k, count, result) |
| 71 | + if *result != "" { // Stop early when k-th happy string is found |
| 72 | + return |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments