package com.fishercoder.solutions;

/**
 * Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

 Example:

 Input: "babad"

 Output: "bab"

 Note: "aba" is also a valid answer.
 Example:

 Input: "cbbd"

 Output: "bb"
 */
public class _5 {

    private int lo, maxLen;

    public String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2)
            return s;

        for (int i = 0; i < len - 1; i++) {
            extendPalindrome(s, i, i); // assume odd length, try to extend Palindrome as possible
            extendPalindrome(s, i, i + 1); // assume even length.
        }
        return s.substring(lo, lo + maxLen);
    }

    private void extendPalindrome(String s, int j, int k) {
        while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
            j--;
            k++;
        }
        if (maxLen < k - j - 1) {
            lo = j + 1;
            maxLen = k - j - 1;
        }
    }

}

@@ -33,16 +33,55 @@
 s;%0A%0A/**%0A
+ * 5. Longest Palindromic Substring%0A *%0A
  * Given
@@ -194,33 +194,32 @@
 000.%0A%0A Example:%0A
-%0A
  Input: %22babad%22%0A
@@ -218,17 +218,16 @@
 %22babad%22%0A
-%0A
  Output:
@@ -233,17 +233,16 @@
 : %22bab%22%0A
-%0A
  Note: %22
@@ -270,16 +270,17 @@
 answer.%0A
+%0A
  Example
@@ -281,17 +281,16 @@
 xample:%0A
-%0A
  Input: 
@@ -296,17 +296,16 @@
  %22cbbd%22%0A
-%0A
  Output:
@@ -351,16 +351,17 @@
 e int lo
+w
 , maxLen
@@ -461,16 +461,18 @@
 len %3C 2)
+ %7B
 %0A       
@@ -485,16 +485,26 @@
 eturn s;
+%0A        %7D
 %0A%0A      
@@ -748,12 +748,14 @@
 g(lo
+w
 , lo
+w
  + m
@@ -821,16 +821,23 @@
 int 
-j
+left
 , int 
-k
+right
 ) %7B%0A
@@ -851,17 +851,20 @@
  while (
-j
+left
  %3E= 0 &&
@@ -864,17 +864,21 @@
 %3E= 0 && 
-k
+right
  %3C s.len
@@ -895,17 +895,20 @@
 .charAt(
-j
+left
 ) == s.c
@@ -913,17 +913,21 @@
 .charAt(
-k
+right
 )) %7B%0A   
@@ -935,17 +935,20 @@
         
-j
+left
 --;%0A    
@@ -955,17 +955,21 @@
         
-k
+right
 ++;%0A    
@@ -995,21 +995,28 @@
 axLen %3C 
-k - j
+right - left
  - 1) %7B%0A
@@ -1033,12 +1033,16 @@
   lo
+w
  = 
-j
+left
  + 1
@@ -1068,13 +1068,20 @@
 n = 
-k - j
+right - left
  - 1

edit 5