【题目】
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000
找出字符串s中的最长回文
【思路】
对字符串进行从左到右顺序遍历;
首先判断当前字符start_index的右侧是否有与其相同的字符串,获取相同部分的长度equalLen,同样为当前最长回文的长度;
其次判断相同回文两端的字符是否相等,若相等,每次回文长度加2;
最后判断当前回文是否比已有的回文长度长,并更新最终结果;
从start_index+equalLen的位置重新开始遍历;
【Java代码】
public class Solution_5_longest_palindrome {
public String longestPalindrome(String s){
String final_result = "";
int start_index = 0; //当前遍历字符位置
while(start_index < s.length()){
int resultLen = 1;
int equalLen = 1; //相同字符的长度
while((start_index+equalLen < s.length())&&(s.charAt(start_index+equalLen) == s.charAt(start_index))){
equalLen += 1;
resultLen += 1;
}
int palin_start = start_index; //回文的起始坐标
int palin_end = start_index+equalLen-1; //回文的结束坐标
while((palin_start - 1 >= 0)&&(palin_end +1 < s.length())&&(s.charAt(palin_start - 1) == s.charAt(palin_end +1))){
resultLen += 2;
palin_start -= 1;
palin_end += 1;
}
if(resultLen > final_result.length())
final_result = s.substring(palin_start,palin_end+1);
start_index += equalLen;
}
return final_result;
}
}