LeetCode: 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, and there exists one unique longest palindromic substring.

 

来来回回用了好长时间。

主要是O(n^2)的两种算法。最后还有一种O(n)的算法,但估计面试的时候是想不出来的,所以就只给个链接。

第一种是用动态规划。O(n^2)时间,O(n^2)空间。

table[i][j]标记string从i到j是不是palindrome。

table[i][j] = table[i+1][j-1] && string[i] == string[j];

初始条件时table[i][i]= true; 这个代表的是一个字符本身是对称的。

table[i][i+1] = string[i] == string[i+1]; 这个代表的是两个字符的情况。

因为每次增长都是已2为单位增长的,所以初始条件既要包括奇数的情况也要包括偶数的情况。

 1 public class Solution {
 2     public static String longestPalindrome(String s) {
 3         if (s.length() < 2) return s;
 4         char[] array = s.toCharArray();
 5         boolean[][] table = new boolean[s.length()][s.length()];
 6         int max = 0;
 7         int index = -1;
 8         
 9         for (int i=0; i<s.length(); i++) table[i][i] = true;
10         
11         for (int i=1; i<s.length(); i++) {
12             if (array[i-1] == array[i]) {
13                 table[i-1][i] = true;
14                 max = 2;
15                 index = i;
16             }
17         }
18         
19         for (int i=1; i<s.length(); i++) {
20             for (int j=0; j<i-1; j++) {
21                 if (array[i] == array[j] && table[j+1][i-1]) {
22                     table[j][i] = true;
23                     if (i-j+1 > max) {
24                         max = i-j+1;
25                         index = i;
26                     }
27                 }
28             }
29         }
30         
31         return s.substring(index-max+1, index+1);
32     }
33 }

 

第二种算法是,以每个位置为中心,向两端扩展,计算以每个位置为中心的最大的palindrome。

时间O(n^2),空间O(1);

 

 1 public class Solution {
 2     public static String longestPalindrome(String s) {
 3         if (s.length() < 2) return s;
 4         String result = "";
 5         
 6         for (int i=0; i<s.length(); i++) {
 7             String s1 = expand(s, i, i);
 8             String s2 = expand(s, i, i+1);
 9             
10             if (s1.length() > result.length()) {
11                 result = s1;
12             }
13             if (s2.length() > result.length()) {
14                 result = s2;
15             }
16         }
17         
18         return result;
19     }
20     
21     public static String expand(String s, int c1, int c2) {
22         int j = 0;
23         for (; c2+j<s.length() && c1-j>=0; j++) {
24             if (s.charAt(c2+j) != s.charAt(c1-j)) {
25                 break;
26             }
27         }
28         
29         return s.substring(c1-j+1, c2+j);    
30     }
31 }

 

 O(n)算法: http://leetcode.com/2011/11/longest-palindromic-substring-part-ii.html

http://www.felix021.com/blog/read.php?2040

posted on 2014-03-15 11:52  longhorn  阅读(166)  评论(0编辑  收藏  举报

导航