5. Longest Palindromic Substring

Description

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

Constraints

Approach

Examples

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Solutions

/**
 * Time complexity : O(n^3)
 * Space complexity : O(1)
 */

class Solution {
    public String longestPalindrome(String s) {
    int maxLen = 0, start = 0, n = s.length();
    for(int i = 0; i < n; i++) {
      for(int j = i+1; j <= n; j++) {
        if((j-i) > maxLen && isPalindrome(s.substring(i, j))) {
          maxLen = j-i;
          start = i;
        }
      }
        if(maxLen == n) break;
    }
    return s.substring(start, start+maxLen);
  }

  public static boolean isPalindrome(String str) {
    int n = str.length();
    for(int i = 0; i < n/2; i++) {
      if(str.charAt(i) != str.charAt(n-i-1)) return false;
    }
    return true;
  }
}

Follow up

  • Longest substring of vowels - GFG

  • Longest Non-palindromic substring - GFG

Last updated

Was this helpful?