forked from wufenggirl/LeetCode-in-Golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindrome-pairs.go
executable file
·66 lines (56 loc) · 1.2 KB
/
palindrome-pairs.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
package problem0336
func palindromePairs(words []string) [][]int {
res := make([][]int, 0, len(words))
size := len(words)
if size < 2 {
return res
}
hash := make(map[string]int, size)
for i := 0; i < size; i++ {
hash[words[i]] = i
}
for i := 0; i < len(words); i++ {
for k := 0; k <= len(words[i]); k++ {
right := words[i][k:]
left := words[i][:k]
if isPalindrome(right) {
leftRev := reverse(left)
if j, ok := hash[leftRev]; ok && i != j {
res = append(res, []int{i, j})
}
}
// 因为
// k == 0 的 right
// 和
// k == len(words[i]) 的 left
// 相等,会导致重复答案
// 需要,len(left) != 0 来过滤掉这种情况
if len(left) != 0 && isPalindrome(left) {
rightRev := reverse(right)
if j, ok := hash[rightRev]; ok && i != j {
res = append(res, []int{j, i})
}
}
}
}
return res
}
func isPalindrome(s string) bool {
i, j := 0, len(s)-1
for i < j {
if s[i] != s[j] {
return false
}
i++
j--
}
return true
}
// 反转字符串
func reverse(s string) string {
bs := []byte(s)
for i, j := 0, len(bs)-1; i < j; i, j = i+1, j-1 {
bs[i], bs[j] = bs[j], bs[i]
}
return string(bs)
}