Longest Palindromic Substring LeetCode

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

 Example 1:

Input: s = "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: s = "cbbd"
Output: "bb"

Example 3:

Input: s = "a"
Output: "a"

Example 4:

Input: s = "ac"
Output: "a"

 NOTE:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters
This problem is very popular in LeetCode, GeeksForGeeks (here and here), and Wikipedia A collection of hundreds of interview questions and solutions are available in our blog at Interview Question Solutions
---------------------------------------------------------------------------
SOLUTION:
class LongestPalindromicSubstring {
    public static String longestPalindrome(String s) {
        if(s == null || s.length() == 0) {
            return "";
        }
       
        String longestPalindromicSubstring = "";
        for(int i = 0; i < s.length(); i++) {
            for(int j = i + 1; j <= s.length(); j++) {
//if this substring is longer than previous palindromesubstring and if this is a palindrome
                if(j - i > longestPalindromicSubstring.length() && isPalindrome(s.substring(i, j))) {
                    longestPalindromicSubstring = s.substring(i, j);
                }
            }
        }
       
        return longestPalindromicSubstring;
    }
   
    public static boolean isPalindrome(String s) {
        int i = 0;
        int j = s.length() - 1;
        while(i <= j) {
            if(s.charAt(i++) != s.charAt(j--)) {
                return false;
            }
        }
       
        return true;
    }

public static void main(String args[]){
String s= "babad";
s = "bbbab";
System.out.println("String :"+s+" has longest palindrome as:"+longestPalindrome(s));
}
}

Source code: Java (solution 1, solution 2)

No comments:

Post a Comment