Given a string s, return the longest palindromic substring in s.

Given a string s, return the longest palindromic substring in s.

Given a string s, return the longest palindromic substring in s.

Given a string s, return the longest palindromic substring in s.


Example 1:


Input: s = "babad"

Output: "bab"

Explanation: "aba" is also a valid answer.


Solution is given below:


class Solution {

    public String longestPalindrome(String s) {

       int start =0, end =0; 

        for(int i=0; i<s.length(); i++){

            int even = expandFromCentre(s, i, i+1);

            int odd = expandFromCentre(s, i, i);

            int len = Math.max(even, odd);

            if(end-start<len){

                start = i - (len-1)/2;

                end = i + len/2;

            }

        }

        return s.substring(start, end+1);

    }


int expandFromCentre(String s, int i, int j){

    while(i>=0 && j<s.length() && s.charAt(i)==s.charAt(j)){

        i--;

        j++;

    }

    return j-i-1;

}

}


Explanation

Palindrome is a word which is same from both left and right sides for example bab.

Substring is a contiguous sequence of characters within a string. For example, "the best of" is a substring of "It was the best of times" whereas "Itwastimes" is a subsequence of "It was the best of times", but not a substring.


We are checking from the middle of a substring if the right side and left side element are same then count their lenght from start and end. In case of even palidrome we are using i, i+1 to compare the right and left characters. 


After this we are returning the indices. and this is how we are calculating the longest palindromic substing in s.


For explanation you can refer the following videos


Hindi

https://youtu.be/AKIHWGumagI


English

https://youtu.be/QfZvw8_jz1w

Load comments