-
Notifications
You must be signed in to change notification settings - Fork 0
/
234-isPalindrome.go
89 lines (80 loc) · 1.52 KB
/
234-isPalindrome.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// https://leetcode.cn/problems/palindrome-linked-list/
package main
import (
"fmt"
"leetcode/util"
)
type ListNode = util.ListNode
/**
* 常规方法。用数组缓存遍历结果,再做比较
* 时间 O(n)
* 空间 O(n)
*/
func isPalindrome2(head *ListNode) bool {
v := []int{}
for node := head; node != nil; node = node.Next {
v = append(v, node.Val)
}
for i, j := 0, len(v)-1; i <= j; i, j = i+1, j-1 {
if v[i] != v[j] {
return false
}
}
return true
}
/**
* 优化空间。反转后半段链表方便做比较,最后再反转回来
* 时间 O(n)
* 空间 O(1)
*/
func isPalindrome(head *ListNode) bool {
if head == nil || head.Next == nil {
return true
}
// 可以用快慢指针,效率更高
length := 0
next := head
for ; next != nil; next = next.Next {
length++
}
var pre, cur *ListNode
next = head
for i := 0; i < length/2; i++ {
pre = cur
cur = next
next = next.Next
cur.Next = pre
}
if length%2 == 1 {
next = next.Next
}
for cur != nil && next != nil {
if cur.Val != next.Val {
return false
}
cur = cur.Next
next = next.Next
}
return true
}
func main() {
a := [][]int{{2}, {1, 2}, {1, 2, 1}, {1, 2, 3, 1}, {1, 2, 2, 1}}
for i := 0; i < len(a); i++ {
head := new(ListNode)
cur := head
for j := 0; j < len(a[i]); j++ {
node := new(ListNode)
node.Val = a[i][j]
node.Next = nil
if j == 0 {
head = node
cur = head
} else {
cur.Next = node
cur = node
}
fmt.Print(a[i][j], " ")
}
fmt.Println("ret:", isPalindrome(head))
}
}