Monday, June 25, 2012

Longest Palindrome Substring size

In this post, I am going to concentrate on longest palindrome substring's size.
Here is the example:
Let the string be "GEEGGEEROREEGOF"
There are two palindromes in this string:
1. GEEG
2. GEEROREEG

A) One approach is to find all substrings --> Filter them for the one that are palindromes --> Find which one of them is longest and we have the answer.
B) The previous one was brute force. Then I come across this link: http://www.geeksforgeeks.org/archives/19155. The guy has explained beautifully. And it worked.
The idea is that start from the two ends and find out if the characters match. Once we have a match, we start finding recursively if that's a palindrome and if we have the longest one.
Here is the code in C++:

#include<iostream>
#include<string>
using namespace std;

int max (int x, int y) { return (x > y)? x : y; }

// Returns the length of the longest palindromic subsequence in seq
int lps(string seq, int i, int j)
{
   // Base Case 1: If there is only 1 character
   if (i == j)
     return 1;

   // Base Case 2: If there are only 2 characters and both are same
   if (seq[i] == seq[j] && i + 1 == j)
     return 2;

   // If the first and last characters match
   if (seq[i] == seq[j])
      return lps (seq, i+1, j-1) + 2;

   // If the first and last characters do not match
   return max( lps(seq, i, j-1), lps(seq, i+1, j) );
}

No comments:

Post a Comment