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"
Let p[i][j] be a table that states whether the substring si…sj is a palindrome or not. Note that any substring of length=1 can be considered as a palindrome. The following equation describes the recurrence.
p[i][j]={true,if l=1si==sj,if l=2p[i+1][j−1]andsi==sj,if len>2
Procedure LONGEST-PALINDROME-SUBSTRING takes a String as it’s input. It stores p[i][j] values in a table p[1…n][1…n] and it computes the entries in row-major order.
**Input:** s input string
**Output:** the longest palindromic substring in s
LONGEST−PALINDROME−SUBSTRING(s)
++ n←s.length
++ let p[1…n][1…n] be a new table
++ start←1
++ l←1
++ `for` i=1 to n
++++ p[i][i]←true
++ `for` i=1 to n−1
++++ p[i][i+1]←si==si+1
++++ `if` p[i][i+1]
++++++ l←2
++++++ start←i
++ `for` len=3 to n
++++ for i=1 to n−len+1
++++++ j←i+len−1
++++++ p[i][j]←si==sjandp[i+1][j−1]
++++++ `if` p[i][j]
++++++++ l←len
++++++++ start←i
++ return sstart…sstart+l−1
And here’s the code.
class LongestPalindromicSubstring { | |
LongestPalindromicSubstring() { | |
throw new AssertionError(); | |
} | |
public static void main(String[] args) { | |
final String s = "babadbabad"; | |
final String p = longestPalindrome(s); | |
System.out.println(p); | |
} | |
public static String longestPalindrome(String s) { | |
final int n = s.length(); | |
final boolean[][] p = new boolean[n][n]; | |
int l = 1; | |
int start = 0; | |
for (int i = 0; i < n; i++) | |
p[i][i] = true; | |
for (int i = 0; i < n - 1; i++) { | |
p[i][i + 1] = s.charAt(i) == s.charAt(i + 1); | |
if (p[i][i + 1]) { | |
l = 2; | |
start = i; | |
} | |
} | |
for (int len = 3; len <= n; len++) { | |
for (int i = 0; i < n - len + 1; i++) { | |
final int j = i + len - 1; | |
p[i][j] = s.charAt(i) == s.charAt(j) && p[i + 1][j - 1]; | |
if (p[i][j]) { | |
start = i; | |
l = len; | |
} | |
} | |
} | |
return s.substring(start, start + l); | |
} | |
} |
Analysis
Time complexity : Θ(n2)Space complexity: Θ(n2) to store the table.
Comments
Post a Comment