46 lines
845 B
Go
46 lines
845 B
Go
// Package q1415 implements a solution for https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/
|
|
package q1415
|
|
|
|
import (
|
|
"math"
|
|
"strings"
|
|
)
|
|
|
|
func getHappyString(n, k int) string {
|
|
// The base is ababababab...
|
|
// Behaves like binary, except the first character, which has three choices: a, b, c.
|
|
// Max of k is 2^n + 2^(n-1)
|
|
|
|
if k > int(math.Pow(2, float64(n))+math.Pow(2, float64(n-1))) {
|
|
return ""
|
|
}
|
|
k -= 1
|
|
|
|
sb := strings.Builder{}
|
|
var last byte
|
|
switch k >> (n - 1) {
|
|
case 0:
|
|
last = 'a'
|
|
case 1:
|
|
last = 'b'
|
|
case 2:
|
|
last = 'c'
|
|
}
|
|
sb.WriteByte(last)
|
|
|
|
lut := [][2]byte{
|
|
{'b', 'c'},
|
|
{'a', 'c'},
|
|
{'a', 'b'},
|
|
}
|
|
|
|
for i := n - 1; i > 0; i-- {
|
|
lookup := k >> (i - 1) & 1
|
|
c := lut[last-'a'][lookup]
|
|
sb.WriteByte(c)
|
|
last = c
|
|
}
|
|
return sb.String()
|
|
}
|
|
|
|
var _ = getHappyString
|