add new solutions
This commit is contained in:
parent
7d2a6718b3
commit
1f0aa6d417
6 changed files with 258 additions and 0 deletions
46
solutions/14/q1415/solution.go
Normal file
46
solutions/14/q1415/solution.go
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue