Manacher’s ALGORITHM 算法实现,空间复杂度 O(2*N+1),时间复杂度O(2*N + 1),经过验证这种算法实现的时间是4ms,而通过最长公共子串算法时间是256ms
func longestPalindrome(s string) string {
n := 2*len(s) + 1
p := make([]int, n+1)
id := 0
mx := 0
for i := 1; i <= n; i++ {
if mx > i {
if p[2*id-i] > mx-i {
p[i] = mx - i
} else {
p[i] = p[2*id-i]
}
} else {
p[i] = 1
}
for {
i1 := i + p[i]
i2 := i - p[i]
var c1 byte
var c2 byte
if i1 < 1 || i1 > n || i2 < 1 || i2 > n {
break
}
if i1&0x1 == 0x01 {
c1 = '#'
} else {
c1 = s[i1/2-1]
}
if i2&0x1 == 0x01 {
c2 = '#'
} else {
c2 = s[i2/2-1]
}
if c1 == c2 {
p[i]++
} else {
break
}
}
if p[i]+i > mx {
mx = p[i] + i
id = i
}
}
max := 0
for i := 1; i <= n; i++ {
if p[i] > p[max] {
max = i
}
}
// for i := 1; i <= n; i++ {
// print(p[i], " ")
// }
// println()
// println(max)
if max&0x1 == 0x1 {
hl := (p[max] - 1) / 2
return s[(max-1)/2-hl : (max+1)/2+hl-1]
} else {
hl := (p[max] - 2) / 2
return s[max/2-hl-1 : max/2+hl]
}
}