mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
58 lines
892 B
Go
58 lines
892 B
Go
|
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]
|
||
|
}
|