-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path131.分割回文串.go
73 lines (64 loc) · 1.23 KB
/
131.分割回文串.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* @lc app=leetcode.cn id=131 lang=golang
*
* [131] 分割回文串
*/
// @lc code=start
package main
import "fmt"
func main() {
var s string
s = "aab"
fmt.Println("%s, %v\n", s, partition(s))
s = "aabba"
fmt.Println("%s, %v\n", s, partition(s))
// var a string
// a = "aa"
// fmt.Printf("%s %t\n", a, Palindrome(a))
// a = "aab"
// fmt.Printf("%s %t\n", a, Palindrome(a))
// a = "aabb"
// fmt.Printf("%s %t\n", a, Palindrome(a))
// a = "a"
// fmt.Printf("%s %t\n", a, Palindrome(a))
// a = ""
// fmt.Printf("%s %t\n", a, Palindrome(a))
}
func partition(s string) [][]string {
final := [][]string{}
if len(s) <= 1 {
final = append(final, []string{s})
return final
}
var dfs func(int, []string)
dfs = func(start int, res []string) {
if start == len(s) {
tmp := make([]string, len(res))
copy(tmp, res)
final = append(final, tmp)
return
}
for i := start + 1; i <= len(s); i++ {
tmp := s[start:i]
if Palindrome(tmp) {
dfs(i, append(res, tmp))
}
}
}
dfs(0, []string{})
return final
}
func Palindrome(s string) bool {
if len(s) <= 1 {
return true
}
n := len(s)
mid := n / 2
for i := 0; i < mid; i++ {
if s[i] != s[n-1-i] {
return false
}
}
return true
}
// @lc code=end