add new solutions

This commit is contained in:
Yiyang Kang 2026-03-21 14:44:38 +09:00
parent 7d2a6718b3
commit 1f0aa6d417
Signed by: kkyy
SSH key fingerprint: SHA256:lJSbAzC3MvrSORdvIVK6h/3g+rVKJNzM7zq0MgA9WKY
6 changed files with 258 additions and 0 deletions

View file

@ -0,0 +1,46 @@
// 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