1.题目
Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
2.解法
思路:从数组开始处作为起点,并跳过与起点处值相等的位置;向前后两边扩散,如果前后两个位置字符相等,向外扩展;遇到前后两个位置处的值不相等的时候结束本轮遍历,并更新最大回文长度max_len和最大的起始点max_left.
时间复杂度为O(N^2)
public class Solution {
public String longestPalindrome(String s) {
int len = s.length();
if(len < 2){
return s;
}
int max_len = 1, max_left = 0, left, right;
for(int start = 0; start < len && len - start > max_len / 2;){
left = right = start;
while(right < len - 1 && s.charAt(right) == s.charAt(right+1))
++right;
start = right + 1;
while(right < len - 1 && left > 0 && s.charAt(right + 1) == s.charAt(left - 1)){
--left;
++right;
}
if(max_len < right - left + 1){
max_len = right - left + 1;
max_left = left;
}
}
return s.substring(max_left, max_left + max_len);
}
}