题目:Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
思路:寻找字符串的最长回文串的题,属于老生常谈的题了,一般要么求出长度为多少,要么求出子串,方法都是一样的:动态规划;中心扩散法;马拉车算法;一般就这三种
算法思想可看我的另一篇博客:最长回文子串
法1:动态规划(时间复杂度O(n^2),空间复杂度O(n^2))
1 class Solution { 2 public static String longestPalindrome(String s){
if(s==null) return null; 3 int n=s.length(); 4 int[][]dp=new int[n+1][n+1]; 5 int max=1; 6 int x=0,y=0; 7 for(int i=0;i<=n;i++){ 8 dp[i][i]=1; 9 } 10 for(int len=2;len<=n;len++){ 11 //len表示子串长度,i表示子串开头位置,j表示子串结束位置 12 for(int i=0;i<=n-len;i++){ 13 int j=i+len-1; 14 //开始比较 15 if(len==2&&s.charAt(i)==s.charAt(j)){ 16 dp[i][j]=2; 17 max=2; 18 x=i; 19 y=j; 20 }else{ 21 if(s.charAt(i)==s.charAt(j)&&dp[i+1][j-1]!=0){ 22 dp[i][j]=len; 23 max=len; 24 x=i; 25 y=j; 26 } 27 } 28 } 29 30 } 31 return s.substring(x,y+1); 32 } 33 }
这种方法看来并不算太好,Your runtime beats 21.57 % of java submissions.
再用中心扩散法试试
Your runtime beats 93.63 % of java submissions
1 public class Solution { 2 int left=0; 3 int max=1; 4 public String longestPalindrome(String s) { 5 char[] cs=s.toCharArray(); 6 for(int i=0;i<cs.length;i++){ 7 findPailndromic(cs,i,i); 8 findPailndromic(cs,i,i+1); 9 } 10 return s.substring(left,left+max); 11 } 12 public void findPailndromic(char[]cs,int i,int j){ 13 while(i>=0&&j<cs.length&&cs[i]==cs[j]){ 14 if(max<j-i+1){ 15 left=i; 16 max=j-i+1; 17 } 18 i--; 19 j++; 20 } 21 } 22 }