問題:給定一個字符串,找出最長的迴文子串
例如:
“babad”的最長迴文子串爲”bab”,當然”aba”也是可以的
解決思路:這種問題要考慮到迴文子串是奇數還是偶數情況,分爲兩種可能。這裏可以採用從內向外擴散的方法來解決該問題。
例如:迴文子串爲奇數,從第一個字符元素開始擴散。第一個子串爲”b”,然後第二個字符元素爲“a”,向左右擴散一位爲”bab”,還是迴文子串,再向左右擴散不滿足迴文條件,則第二個迴文子串爲“bab”,重複上述操作。迴文子串爲偶數情況與上述類似。
class Solution {
public static String longestPalindrome(String s) {
int len = s.length();//字符串長度
int maxlen= 1;//最長子串長度
int start = 0;
//迴文爲奇數
for(int i = 0;i<len;i++){
int first = i-1;//左指針
int last = i+1;//右指針
//向外擴散
while(first>=0 && last<len&&s.charAt(first)==s.charAt(last)){
if(maxlen<last-first+1){
maxlen = last - first+1;
start = first;
}
first--;
last++;
}
}
//迴文爲偶數
for(int i = 0;i<len;i++){
int first = i;
int last = i+1;
while(first>=0&& last<len&&s.charAt(first)==s.charAt(last)){
if(maxlen<last-first+1){
maxlen = last - first+1;
start = first;
}
first--;
last++;
}
}
//輸出子串
if(len>0){
return s.substring(start,maxlen+start);
}
return null;
}
}