1

Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.

How and what i did? I only know how to find a palindrome i.e.

Given a String.I took 2 index i,j starting from 0 and length-1.Comparing both characters present at the given index till i

Here is my code

 class StringPallendrome 
{
 static int length = 0;
 static int Count=0;
 static boolean stringpallendrome(String p) 
 {

    boolean flag=false;
    boolean s3 = true;
    boolean s4 = false;
    char ch[] = p.toCharArray();
    for(int i=0,j=ch.length-1;i<j;i++,j--) 
      { 
       if(ch[i]==ch[j])
       { 
          flag=true;
          length++;
       } 
       else
       {
          flag=false;
          break;
       }
      }
      if(flag==true)
      {
            System.out.println("Its a pallendrome");
            return s3;

      }
      else
      {

          return s4;
      }
 }

public static void main(String s[]) 
 {
    boolean s2;
    String a = new String("abac");
    s2 = stringpallendrome(a);
    System.out.println(s2);
 }
}

I searched various sites for this problem and found them useful but could not understand.

http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html

My domain for this problem is code in java with a simple brute force solution and then use a o(n2) approach with no extra space just like this present too. http://www.geeksforgeeks.org/longest-palindromic-substring-set-2/

5 Answers5

5

This is a redundant question. You can find the answer here. Write a function that returns the longest palindrome in a given string

Btw the answer is

You can find the the longest palindrome using Manacher's Algorithm in O(n) time! Its implementation can be found here and here. For input String s = "HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE". It finds the correct output which is 1234567887654321.

Community
  • 1
  • 1
Emdadul Sawon
  • 5,730
  • 3
  • 45
  • 48
  • Yes,Question is redundant.I haven't asked for any Manacher's Algorithm in O(n).I was only interested in understanding the bruteForce solution as well as O(n2) approach with no extra space.The former i understood from the redundant question but the latter is still not understood.I have provided a link in my question from where i understood in java. – javaCoderMakeSimple Aug 04 '15 at 07:56
2

See Manacher's algorithm.

Its time complexity is O(n).

John Woo
  • 446
  • 3
  • 13
1

Here's an example of pseudocode to find longest 'even' length palindrome, you can write something very similar for longest odd length palindrome.

enum State = {INCREMENT, EXPAND, RESET}  // different states of the algorithm

int longestEvenPalindrome(String s){
    int p1 = 0, p2 = 1, p3 = 1, longestPalindrome = 1;
    State state = INCREMENT;

    while(p2 < s.length){
        switch(state){
            case INCREMENT:                    // Incr. until matching chars
                if(s[p1] == s[p2]){
                    state = EXPAND;
                    p3 = p2 + 1;
                } else {
                    p1++;
                    p2++;
                }
                break;

            case EXPAND:                      // Expand until mismatching chars
                if(p1 < 0 || s[p1] != s[p2]){
                    state = RESET;
                } else {
                    p1--; // Expand Left
                    p2++; // Expand Right
                }
                break;

            case RESET:
                longestPalindrome = Math.max(longestPalindrome, p2 - p1 - 2);
                p2 = p3;
                p1 = p3 - 1;
                state = INCREMENT;
                break;
        }
    }

    return longestPalindrome;
}
bcorso
  • 45,608
  • 10
  • 63
  • 75
1

First of all, checking if a string is a palindrome can be done with:

static boolean isPalindrome(String p) {
    return p.equals(new StringBuilder(p).reverse().toString());
}

Your question should be : "How to find longest palindrome efficiently?". Typically it is done with Manacher algorithm. Good implementation has been written by Robert Sedgewick and Kevin Wayne:

/******************************************************************************
 *  Compilation:  javac Manacher.java
 *  Execution:    java Manacher text
 *  Dependencies: StdOut.java
 *
 *  Computes the longest palindromic substring in linear time
 *  using Manacher's algorithm.
 *
 *  Credits: The code is lifted from the following excellent reference
 *  http://www.leetcode.com/2011/11/longest-palindromic-substring-part-ii.html
 *
 ******************************************************************************/

public class Manacher {
    private int[]  p;  // p[i] = length of longest palindromic substring of t, centered at i
    private String s;  // original string
    private char[] t;  // transformed string

    public Manacher(String s) {
        this.s = s;
        preprocess();
        p = new int[t.length];

        int center = 0, right = 0;
        for (int i = 1; i < t.length-1; i++) {
            int mirror = 2*center - i;

            if (right > i)
                p[i] = Math.min(right - i, p[mirror]);

            // attempt to expand palindrome centered at i
            while (t[i + (1 + p[i])] == t[i - (1 + p[i])])
                p[i]++;

            // if palindrome centered at i expands past right,
            // adjust center based on expanded palindrome.
            if (i + p[i] > right) {
                center = i;
                right = i + p[i];
            }
        }

    }

    // Transform s into t.
    // For example, if s = "abba", then t = "$#a#b#b#a#@"
    // the # are interleaved to avoid even/odd-length palindromes uniformly
    // $ and @ are prepended and appended to each end to avoid bounds checking
    private void preprocess() {
        t = new char[s.length()*2 + 3];
        t[0] = '$';
        t[s.length()*2 + 2] = '@';
        for (int i = 0; i < s.length(); i++) {
            t[2*i + 1] = '#';
            t[2*i + 2] = s.charAt(i);
        }
        t[s.length()*2 + 1] = '#';
    }

    // longest palindromic substring
    public String longestPalindromicSubstring() {
        int length = 0;   // length of longest palindromic substring
        int center = 0;   // center of longest palindromic substring
        for (int i = 1; i < p.length-1; i++) {
            if (p[i] > length) {
                length = p[i];
                center = i;
            }
        }
        return s.substring((center - 1 - length) / 2, (center - 1 + length) / 2);
    }

    // longest palindromic substring centered at index i/2
    public String longestPalindromicSubstring(int i) {
        int length = p[i + 2];
        int center = i + 2;
        return s.substring((center - 1 - length) / 2, (center - 1 + length) / 2);
    }



    // test client
    public static void main(String[] args) {
        String s = args[0];
        Manacher manacher = new Manacher(s);
        StdOut.println(manacher.longestPalindromicSubstring());
        for (int i = 0; i < 2*s.length(); i++)
            StdOut.println(i +  ": " + manacher.longestPalindromicSubstring(i));

    }
}

Source : http://algs4.cs.princeton.edu/53substring/Manacher.java.html

Margus
  • 19,694
  • 14
  • 55
  • 103
0
class LongPal
{
    public static void main (String args[])
    {
        String k = new String("abcertmadamelkokokp"); //random string 
        boolean flag = false; //flag to check whether isPalindrome is true
        int i, j , max_pal =0; //max_pal keeps account of length of the longest palindrome
        String s =""; 
        String s1 = ""; //two strings

        LongPal obj = new LongPal();

        for (i=0;i<k.length();i++) //outer loop starts from index 0 of the string
        {
            for (j=k.length();j>i+1;j--) //inner loop starts from the end of the string
            {


                flag = obj.isPalindrome(k.substring(i,j)); //sending the substring to isPalindrome
                if (flag)
                {

                    s= k.substring(i,j); //storing the palindrome  substring in s

                        if(s.length()>max_pal) // if the palindrome encountered has a length more than the previously encountered palindrome
                        {
                         max_pal = s.length(); //set max_pal to the length of the new palindrome
                         s1 = s; //store the new palindrome in s1
                        }

                }       


            }
        }


        System.out.println("Longest Palindrome:  "+ s1); //print the longest palindrome

    }



    public boolean isPalindrome(String s)
    {
        StringBuffer s1 = new StringBuffer(s); //copy String s to StringBuffer s1
        StringBuffer s2 = new StringBuffer(s);//copy String s to StringBuffer s2

    String rev=s2.reverse().toString(); //reverse s2 and convert it into string type and store the same in rev

         if (s1.toString().equals(rev)) //convert s1 to string and compare with rev. You can't use .equals() for StringBuffer type. 

         {  

             return true;
         }
         else
         {

             return false;
         }
    }



}