操操操

Manacher算法golang版本

2023-08-20
1分钟阅读时长
func longestPalindrome(s string) string{
    tmpString := "$#"
    for s :=0;i<len(s);i++{
        tmpString += string(s[i])
        tmpString += "#"
    }
    tmpString += "&"
    p := make([]int,len(tmpString))
    mx, id := 0,0
    maxLength,maxIndex :=0,0
    for i :=1;i<len(tmpString);i++{
        if mx < i {
            p[i] = i 
        }else{
            if (mx - i) < p[(2*id-i)]{
                p[i] = mx - i 
            }else{
                p[i] = p[2*id-i]
            }
            for j := p[i];i+j<len(tmpString) && j < i;j++{
                if tmpString[i+j] == tmpString[i-j]{
                    p[i]++
                }else{
                    break
                }
            }
        }
        if mx < (i+p[i]){
            id = i 
            mx = i + p[i]
        }
        if p[i] > (maxLength){
            maxLength = p[i]
            maxIndex = (i - p[i]) / 2
        }
    }

    resultString := ""
    for k :=0;k<maxLength-1;k++{
        resultString += string(s[maxIndex+k])
    }
    return resultString
}
Avatar

Aisen

Be water,my friend.