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


Test Cases

Example 1:

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

Example 2:

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

Solution

class Solution {
public:
    string longestPalindrome(string s) {
        int n = s.length(), start = 0, end=0;
        bool dp[n][n];
        memset(dp, false, sizeof(dp));
        for(int i=n-1; i>=0; i--) {
            for(int j=i; j<n; j++) {
                if (s[i] == s[j] && (j-i <= 2 || dp[i+1][j-1])) {
                    dp[i][j] = true;
                }
                if (dp[i][j] && j-i > end-start) {
                    end = j;
                    start = i;
                }
            }
        }
        return s.substr(start, end-start+1);
    }
};
class Solution {
    public String longestPalindrome(String s) {
        int n = s.length(), start = 0, end=0;
        boolean[][] dp = new boolean[n][n];
        for(int i=n-1; i>=0; i--) {
            for(int j=i; j<n; j++) {
                if (s.charAt(i) == s.charAt(j) && (j-i <= 2 || dp[i+1][j-1])) {
                    dp[i][j] = true;
                }
                if (dp[i][j] && j-i > end-start) {
                    end = j;
                    start = i;
                }
            }
        }
        return s.substring(start, end+1);
    }
}
class Solution:
    def longestPalindrome(self, s: str) -> str:
        n, start, end = len(s), 0, 0
        dp = [[0 for _ in range(n)] for _ in range(n)]
        for i in range(n-1, -1, -1):
            for j in range(i, n):
                if s[i] == s[j] and (j-i <= 2 or dp[i+1][j-1]):
                    dp[i][j] = True
                if dp[i][j] and j-i > end-start:
                    start, end = i, j
        return s[start:end+1]
Time Complexity: O(n2)
Space Complexity: O(n2)