首页 > 代码库 > leetcode longest palindromic substring (medium) /java

leetcode longest palindromic substring (medium) /java

最长回文字串

上题:

技术分享

测试用例中,注意aaabaaaa。

但是我time limit exceeded。用了极暴力的方法解。(三层循环)找每一个字符的最长回文字串。

技术分享
 1 /**
 2 * 最长回文子串
 3 * 2017-5-7
 4 **/
 5 
 6 import java.io.*;
 7 import java.util.*;
 8 import java.lang.*;
 9 
10 public class Solution
11 {
12     public static String longestPalindrome(String s)
13     {
14         int len=s.length();
15         char[] c=s.toCharArray();
16         String str=new String("hz");
17         int max=0;
18         int from=0,to=0;
19         int i,j,ii,jj;
20         for(i=0;i<len-1;i++)
21         {
22             ii=i;
23             for(j=len-1;j>0;j--)
24             {
25                 jj=j;
26                 while(c[i]==c[j]&&i<j-1)
27                 {
28                     i++;j--;
29                 }
30                 //System.out.println("i:"+i+"--j:"+j);
31                 if(((i==j||(i+1==j&&(c[i]==c[j])))&&jj-ii>max))
32                 {
33                     max=jj-ii;
34                     from=ii;
35                     to=jj;
36                     //System.out.println(max+" -- "+ii+" -- "+jj);
37                 }
38                 i=ii;
39                 j=jj;
40 
41             }
42         }
43         //System.out.println(from+" -- "+to);
44         str=s.substring(from,to+1);
45         return str;
46 
47     }
48     public static void main(String[] args)
49     {
50 
51         System.out.println(longestPalindrome("aaabaaaa"));
52     }
53 
54 }
View Code

挂在超级长的用例上了。

技术分享

决定用动态规划。

【待更新】

 

leetcode longest palindromic substring (medium) /java