Longest Palindromic Substring

A palindrome is a nonempty string over some alphabet that reads the same forward and backward. Examples of palindromes are all strings of length 1, civic, racecar, and aibohphobia (fear of palindromes).

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 sisj 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][j1]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[1n][1n] and it computes the entries in row-major order. 

 
**Input:** s input string  
**Output:** the longest palindromic substring in s  
LONGESTPALINDROMESUBSTRING(s)  
++ ns.length  
++ let p[1n][1n] be a new table   
++ start1  
++ l1  
++  `for` i=1 to n      
++++ p[i][i]true  
++  `for` i=1 to n1      
++++ p[i][i+1]si==si+1  
++++ `if` p[i][i+1]  
++++++  l2  
++++++ starti  
++  `for` len=3 to n  
++++ for i=1 to nlen+1  
++++++ ji+len1  
++++++ p[i][j]si==sjandp[i+1][j1]   
++++++ `if` p[i][j]  
++++++++ llen  
++++++++  starti  
++ return sstartsstart+l1

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

Popular posts from this blog

Introducing Java Reactive Extentions in to a SpringBoot Micro Service

Combining the emissions of multiple Observables together using RxJava Zip operator in a Spring Boot Micro service

RabbitMQ Transport in WSO2 ESB