manacher算法注意事項

manacher算法注意事項

manacher算法用來求解一個字符串中的最長迴文子串,類似12421,迴文最大長度爲5.

/*
*第一步:將字符串改寫爲奇數個數,簡化問題,不用考慮偶數的情況,坑點:必須額外添加的字符出現在首位,如:#1#2#4#2#1#,如果寫成1#2#4#2#1,最後結果會出現問題。
*第二步:對處理後的字符串求迴文長度。對每一個i>=0&&i<len的字符,以該字符爲軸求取回文長度。坑點:應用公式m[i]= min(last-i,m[2*i-j])的條件是i<last,不是2*i-j>=0,不滿足i<last條件時m[i] = 1,不是 0 ;更新last時候,判斷條件是 i + m[i] > last   ,不是 m[i] > last .
*/
string mfill(string s){
    int len = s.size();
    string res;
    for(int i = 0 ; i< len ;++i){
        res+='#';
        res+=s[i];
    }
    return res+'#';
}
int mf(string s){
    s = mfill(s);
    int len = s.size();
    int m[len];
    m[0] = 1;
    int last = 0;
    int res = 0;
    int i = 0;
    int j = 0;
    while(j<len){
        int r = 1;
        if(last>j)
            r  = min(last-j,m[2*i-j]);//last < j+m[2*i-j]?last-j:m[2*i-j];
        while(j+r<len && j-r>=0 && s[j+r] == s[j-r]) ++r;
        m[j] = r;
        //cout<<m[j]<<endl;
        if(j+m[j]>last){
            i = j;
            last = j+m[j];
        }
        if(m[j] > res){
            res = m[j];
        }
        ++j;
    }
    return res-1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章