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"
create a videp on the solution of the program
视频信息
答案文本
视频字幕
Today we'll solve the longest palindromic substring problem. Given a string, we need to find the longest substring that reads the same forward and backward. For example, in the string "babad", both "aba" and "bab" are valid palindromes of length 3.
The expand around center approach is efficient for this problem. The key insight is that every palindrome expands around its center. For each position in the string, we check for both odd-length palindromes with a single character center, and even-length palindromes with the center between two characters. We expand outward as long as characters match on both sides.
Here's the complete implementation. The main function iterates through each position and checks for both odd and even length palindromes using the expand around center helper function. The helper function expands outward while characters match and returns the length. We keep track of the longest palindrome found and return the corresponding substring. The time complexity is O(n squared) and space complexity is O(1).
Let's trace through the algorithm with the example "babad". We check each position as a potential center. At position 0, we find only 'b'. At position 1, we find 'a'. At position 2, expanding around 'b' gives us the palindrome "bab". At position 3, expanding around 'a' gives us "aba". Both have length 3, so either is a valid answer. The algorithm correctly identifies the longest palindromic substring.
To summarize, the expand around center approach has O(n squared) time complexity since we check each position and expand up to n characters. The space complexity is O(1) as we only use constant extra space. This solution is simple, intuitive, and handles both odd and even length palindromes efficiently. It works well for most practical inputs and is the preferred approach for this problem.