go: add «664. Strange Printer»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-21 12:51:31 +02:00
parent 38d191ac6b
commit 34b86138ef
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

57
go/strange-printer.go Normal file
View file

@ -0,0 +1,57 @@
package main
import "strings"
func strangePrinter(s string) int {
mergeConsecutive := func() string {
withoutConsecutive := strings.Builder{}
for i := 0; i < len(s); {
c := s[i]
withoutConsecutive.WriteByte(c)
for i < len(s) && s[i] == c {
i++
}
}
return withoutConsecutive.String()
}
compute := func(s string, dp [][]int, length int) {
for l := 0; l+length-1 < len(s); l++ {
r := l + length - 1
dp[l][r] = length
for mid := 0; mid < length-1; mid++ {
turns := dp[l][l+mid] + dp[l+mid+1][r]
if s[l+mid] == s[r] {
turns--
}
dp[l][r] = min(
dp[l][r],
turns,
)
}
}
}
s = mergeConsecutive()
n := len(s)
// Make a DP table
dp := make([][]int, n)
for i := range n {
dp[i] = make([]int, n)
dp[i][i] = 1
}
for length := 2; length <= n; length++ {
compute(s, dp, length)
}
return dp[0][n-1]
}