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.
求s中最长回文子串,如abccba或aba;刚开始使用暴力算法发现超时,可以考虑遍历2n+1个中心,并以此中心求出该中心的最长回文串,代码如下:
public class Solution { public String subPalindrome(String s,int i,int j) { while(i>=0&&j<=s.length()-1&&s.charAt(i)==s.charAt(j)) { i--; j++; } return s.substring(i+1,j); } public String longestPalindrome(String s) { int size = s.length(); String re = ""; for(int i=0;i<size;i++) { String substring = subPalindrome(s,i,i+1); if(substring.length()>re.length()) re = substring; substring = subPalindrome(s,i-1,i+1); if(substring.length()>re.length()) re = substring; } return re; } }
若想达到线性复杂度可以考虑使用曼彻斯特算法。