mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
go: add «664. Strange Printer»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
38d191ac6b
commit
34b86138ef
1 changed files with 57 additions and 0 deletions
57
go/strange-printer.go
Normal file
57
go/strange-printer.go
Normal 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]
|
||||||
|
}
|
Loading…
Reference in a new issue