Original address: Longest palindromic Substring | Set 1
A string is known. Locate the longest palindrome substring in this string. For example, if the known string is: "Forgeeksskeegfor", then the output should be: "Geeksskeeg".
Method 1 (Violence law)
The simplest way is to test each substring to see if they are a palindrome. We can use a three-layer loop, the outer two loops according to the fixed corner character to find all the substrings, the most internal loop is to check whether the substring is a palindrome.
Complexity of Time: O (n^3)
Space complexity: O (1)
Method 2 (Dynamic planning)
This problem can reduce the complexity of the time by the result of the deposit sub-problem. We will maintain a Boolean array of type Table[n][n], which is filled from the bottom up. If the substring is Huineven, then Table[i][j] is true. In order to calculate table[i][j], we first check the value of table[i+1][j-1], if this value is true, and str[i] is the same as str[j], then Table[i][j] is true. Otherwise, the value of Table[i][j] is false.
A Dynamic Programming solution for longest palindr. This code was adopted from following link//http://www.leetcode.com/2011/11/ longest-palindromic-substring-part-i.html #include <stdio.h> #include <string.h>//A utility function to PR int a substring str[low. High] void Printsubstr (char* str, int. Low, int.) {for (int i = low; I <= high; ++i) printf ("%c", str[
I]);
}//This function prints the longest palindrome substring//of str[]. It also returns the length of the longest palindrome int longestpalsubstr (char *str) {int n = strlen (str);//GE T length of input string//TABLE[I][J] would be false if substring str[i.
J]//Is not palindrome.
Else Table[i][j] would be true bool Table[n][n];
memset (table, 0, sizeof (table));
All substrings of length 1 is palindromes int maxLength = 1;
for (int i = 0; i < n; ++i) table[i][i] = true;
Check for sub-string of length 2. int start= 0;
for (int i = 0; i < n-1; ++i) {if (str[i] = = Str[i+1]) {table[i][i+1] = true;
start = i;
MaxLength = 2; }}//Check for lengths greater than 2. K is length//of substring for (int k = 3; k <= N; ++k) {//Fix the starting index for (i NT i = 0; i < n-k+1;
++i) {//Get the ending index of substring from//starting index I and length k
Int J = i + k-1; Checking for sub-string from ith Index to//JTH index IFF str[i+1] to Str[j-1 "is a//Palindr
ome if (table[i+1][j-1] && str[i] = = Str[j]) {table[i][j] = true;
if (k > maxLength) {start = i;
MaxLength = k;
}}}} printf ("Longest palindrome substring is:"); PRintsubstr (str, start, start + maxLength-1); return maxLength;
return length of LPS}//Driver program to test above functions int main () {char str[] = "forgeeksskeegfor";
printf ("\nlength is:%d\n", Longestpalsubstr (str));
return 0; }
Output:
Longest palindrome substring Is:geeksskeeg
Length is:10
Complexity of Time: O (n^2)
Space complexity: O (n^2)