132.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package main
  2. func minCutSlow(s string) int { // Too slow :(
  3. n := len(s)
  4. if n <= 1 {
  5. return 0
  6. }
  7. cutCnt := make([]int, n+1)
  8. cutCnt[0] = 1
  9. for i := 0; i < n; i++ {
  10. if cutCnt[i] != 0 {
  11. for j := i + 1; j <= n; j++ {
  12. if isPalindrome(s, i, j) {
  13. if cutCnt[j] == 0 {
  14. cutCnt[j] = cutCnt[i] + 1
  15. } else if cutCnt[i] < cutCnt[j] {
  16. cutCnt[j] = cutCnt[i] + 1
  17. }
  18. }
  19. }
  20. }
  21. }
  22. return cutCnt[n] - 2
  23. }
  24. func isPalindrome(s string, beg, end int) bool { // End is not included
  25. for ; beg < end; beg, end = beg+1, end-1 {
  26. if s[beg] != s[end-1] {
  27. return false
  28. }
  29. }
  30. return true
  31. }
  32. func minCut(s string) int {
  33. n := len(s)
  34. if n <= 1 {
  35. return 0
  36. }
  37. dp := make([]int, n+1)
  38. for i := 0; i <= n; i++ {
  39. dp[i] = i - 1
  40. }
  41. for i := 0; i < n; i++ {
  42. // For example, 'aba' and i = 1
  43. for j := 0; 0 <= i-j && i+j < n && s[i-j] == s[i+j]; j++ {
  44. if dp[i-j] < dp[i+j+1] {
  45. dp[i+j+1] = dp[i-j] + 1
  46. }
  47. }
  48. // For example, 'abba' and i = 1
  49. for j := 1; 0 <= i-j+1 && i+j < n && s[i-j+1] == s[i+j]; j++ {
  50. if dp[i-j+1] < dp[i+j+1] {
  51. dp[i+j+1] = dp[i-j+1] + 1
  52. }
  53. }
  54. }
  55. return dp[n]
  56. }
  57. // func main() {
  58. // println(minCut("abb"))
  59. // println(minCut("aab"))
  60. // println(minCut("abbbbbb"))
  61. // }