-
Notifications
You must be signed in to change notification settings - Fork 21
/
LongestPalindromicSubstring.go
40 lines (35 loc) 路 930 Bytes
/
LongestPalindromicSubstring.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
package LongestPalindromicSubstring
func longestPalindrome(s string) string {
array := []byte(s)
arrayLength := len(array)
if arrayLength <= 1 {
return s
}
var maxLength = 0
var startIndex = 0
for index := 0; index < arrayLength; index++ {
var leftIndex = index
var rightIndex = index
for ; leftIndex >= 0 && rightIndex < arrayLength && array[leftIndex] == array[rightIndex]; {
current := rightIndex - leftIndex + 1
if current > maxLength {
maxLength = current
startIndex = leftIndex
}
leftIndex -= 1
rightIndex += 1
}
leftIndex = index
rightIndex = index + 1
for ; leftIndex >= 0 && rightIndex < arrayLength && array[leftIndex] == array[rightIndex]; {
current := rightIndex - leftIndex + 1
if current > maxLength {
maxLength = current
startIndex = leftIndex
}
leftIndex -= 1
rightIndex += 1
}
}
return string(array[startIndex:startIndex+maxLength])
}