求解最長的回文子串

2021-08-18 20:17:55 字數 1197 閱讀 8043

1.暴力法

找出所有子串,並且判斷是否是回文子串,並且記錄最長長度,演算法複雜度為o(n^3),強烈不推薦。

2.對稱求解法

遍歷字串每個位置,從每個位置向兩邊擴散,判斷是否對稱,演算法複雜度為o(n^2),但是需要考慮長度為奇偶兩種情況。

示例**:

public int longestpalindrome(string str)

int result=0;

int max=0;

//遍歷所有位置

for(int i=0;i//考慮str長度為奇數的情況,j為兩邊移動的距離

for(int j=0;j<=i&&i+jif(str.charat(i-j)!=str.charat(i+j))

max=j*2+1;

}if(max>result)

//考慮str長度為偶數的情況,j為移動的距離

for(int j=0;j<=i&&i+j+1if(str.charat(i-j)!=str.charat(i+j+1))

max=j*2+2;

}if(max>result)

result=max;

}return result;

}3.manacher演算法

從解法2我們可以發現仍有很多子串被重複判斷,所以就引入了manacher演算法。

第乙個不同:首先manacher演算法為了解決奇偶問題在原字串中插入了#符號,將字串長度統一為奇數,例如將字串abcbae擴充為#a#b#c#b#a#e#

第二個不同:manacher演算法引入了乙個回文半徑,即用乙個陣列儲存每個字元的回文半徑,回文半徑初始化為1,(本身),求解回文半徑方法見**注釋。

for (int i = 0; i < str2.length(); i ++)

// 向兩邊進行匹配

while (i - r >= 0 && i + r < str2.length() && str2.charat(i - r) == str2.charat(i + r))

// 如果掃瞄結束後位置大於right,需要更新right和center

if (i + r - 1> right)

rad[i] = r;

}// 掃瞄最大長度

int result = 0;

for (int r : rad)

}return result - 1;

}

最長回文串 演算法 4 求解最長回文子串

問題描述 給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。注釋 回文通俗的說就是正著念和反著念都一樣,如 上海自來水來自海上。示例 1 輸入 dabccbac 輸出 abccba 示例 2 輸入 cbbd 輸出 bb 解題思路 此處撰寫解題思路 遍歷每乙個索引,...

3種解法 求解最長回文子串

給定乙個字串 s,找到 s 中最長的回文子串。你可以假設 s 的最大長度為 1000。示例 1 輸入 babad 輸出 bab 注意 aba 也是乙個有效答案。示例 2 輸入 cbbd 輸出 bb 思路 原理就是對字串從前到後依次進行遍歷,最外層迴圈為子串頭,第二層迴圈為確定子串尾,第三層迴圈為確定...

最長回文子串 最長回文子串行

1.最長回文子串行 可以不連續 include include include include using namespace std 遞迴方法,求解最長回文子串行 intlps char str,int i,int j intmain include include include using n...