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] }