Monday, June 25, 2018

Longest Palindromic Substring

Problem statement: Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
  1. import java.io.IOException;
  2. public class LongestSubstringPalindrome
  3. {
  4.   public static void main(String[] args) throws IOException
  5.   {
  6.     // String word = "abbcbba";
  7.     String str = "abbagoodteacher";
  8.     System.out.println(longestPalindrome(str));
  9.   }
  10.   public static String longestPalindrome(String s)
  11.   {
  12.     int length = s.length();
  13.     if (s == null || length < 2)
  14.     {
  15.       return s;
  16.     }
  17.     boolean isPalindrome[][] = new boolean[length][length];
  18.     int left = 0;
  19.     int right = 0;
  20.     for (int j = 1; j < length; j++)
  21.     {
  22.       for (int i = 0; i < j; i++)
  23.       {
  24.         boolean isInnerWordPalindrome = isPalindrome[i + 1][j - 1] || j - i <= 2;
  25.         if (s.charAt(i) == s.charAt(j) && isInnerWordPalindrome)
  26.         {
  27.           isPalindrome[i][j] = true;
  28.           if (j - i > right - left)
  29.           {
  30.             left = i;
  31.             right = j;
  32.           }
  33.         }
  34.       }
  35.     }
  36.     return s.substring(left, right + 1);
  37.   }
  38. }
Output: abba

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...