📑 题目:131. 分割回文串

🚀 本题 LeetCode 传送门

题目大意

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。

解题思路

  • 要求输出一个字符串可以被拆成回文串的所有解,DFS 递归求解即可。

代码

  1. package leetcode
  2. // 解法一
  3. func partition131(s string) [][]string {
  4. if s == """" {
  5. return [][]string{}
  6. }
  7. res, pal := [][]string{}, []string{}
  8. findPalindrome(s, 0, """", true, pal, &res)
  9. return res
  10. }
  11. func findPalindrome(str string, index int, s string, isPal bool, pal []string, res *[][]string) {
  12. if index == len(str) {
  13. if isPal {
  14. tmp := make([]string, len(pal))
  15. copy(tmp, pal)
  16. *res = append(*res, tmp)
  17. }
  18. return
  19. }
  20. if index == 0 {
  21. s = string(str[index])
  22. pal = append(pal, s)
  23. findPalindrome(str, index+1, s, isPal && isPalindrome131(s), pal, res)
  24. } else {
  25. temp := pal[len(pal)-1]
  26. s = pal[len(pal)-1] + string(str[index])
  27. pal[len(pal)-1] = s
  28. findPalindrome(str, index+1, s, isPalindrome131(s), pal, res)
  29. pal[len(pal)-1] = temp
  30. if isPalindrome131(temp) {
  31. pal = append(pal, string(str[index]))
  32. findPalindrome(str, index+1, temp, isPal && isPalindrome131(temp), pal, res)
  33. pal = pal[:len(pal)-1]
  34. }
  35. }
  36. return
  37. }
  38. func isPalindrome131(s string) bool {
  39. slen := len(s)
  40. for i, j := 0, slen-1; i < j; i, j = i+1, j-1 {
  41. if s[i] != s[j] {
  42. return false
  43. }
  44. }
  45. return true
  46. }
  47. // 解法二
  48. func partition131_1(s string) [][]string {
  49. result := [][]string{}
  50. size := len(s)
  51. if size == 0 {
  52. return result
  53. }
  54. current := make([]string, 0, size)
  55. dfs131(s, 0, current, &result)
  56. return result
  57. }
  58. func dfs131(s string, idx int, cur []string, result *[][]string) {
  59. start, end := idx, len(s)
  60. if start == end {
  61. temp := make([]string, len(cur))
  62. copy(temp, cur)
  63. *result = append(*result, temp)
  64. return
  65. }
  66. for i := start; i < end; i++ {
  67. if isPal(s, start, i) {
  68. dfs131(s, i+1, append(cur, s[start:i+1]), result)
  69. }
  70. }
  71. }
  72. func isPal(str string, s, e int) bool {
  73. for s < e {
  74. if str[s] != str[e] {
  75. return false
  76. }
  77. s++
  78. e--
  79. }
  80. return true
  81. }