leetcode-5-Longest Palindromic Substring
阿新 • • 發佈:2018-05-27
tar 空間復雜度 lan long 最長回文子串 最長回文 算法 bmi solution
題目: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 }
leetcode-5-Longest Palindromic Substring