LeetCode 0005. Longest Palindromic Substring Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0

Description

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.

Example 2:

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

 

Constraints:

  • 1 <= s.length <= 1000
  • s consist of only digits and English letters.

Solutions

Solution 1: Dynamic Programming

We define f[i][j] to represent whether the string s[i..j] is a palindrome, initially f[i][j] = true.

Next, we define variables k and mx, where k represents the starting position of the longest palindrome, and mx represents the length of the longest palindrome. Initially, k = 0, mx = 1.

Considering f[i][j], if s[i] = s[j], then f[i][j] = f[i + 1][j - 1]; otherwise, f[i][j] = false. If f[i][j] = true and mx < j - i + 1, then we update k = i, mx = j - i + 1.

Since f[i][j] depends on f[i + 1][j - 1], we need to ensure that i + 1 is before j - 1, so we need to enumerate i from large to small, and enumerate j from small to large.

The time complexity is O(n^2), and the space complexity is O(n^2). Here, n is the length of the string s.

PythonJavaC++GoTypeScriptRustJavaScriptC#CNim
class Solution: def longestPalindrome(self, s: str) -> str: n = len(s) f = [[True] * n for _ in range(n)] k, mx = 0, 1 for i in range(n - 2, -1, -1): for j in range(i + 1, n): f[i][j] = False if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] if f[i][j] and mx < j - i + 1: k, mx = i, j - i + 1 return s[k : k + mx](code-box)

Solution 2: Enumerate Palindrome Midpoint

We can enumerate the midpoint of the palindrome, spread to both sides, and find the longest palindrome.

The time complexity is O(n^2), and the space complexity is O(1). Here, n is the length of the string s.

PythonJavaC++GoRustC#PHP
class Solution: def longestPalindrome(self, s: str) -> str: def f(l, r): while l >= 0 and r < n and s[l] == s[r]: l, r = l - 1, r + 1 return r - l - 1 n = len(s) start, mx = 0, 1 for i in range(n): a = f(i, i) b = f(i, i + 1) t = max(a, b) if mx < t: mx = t start = i - ((t - 1) >> 1) return s[start : start + mx](code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !