Leetcode 5. Longest Palindromic Substring
Given a string s
, return the longest palindromic substring in s
.
s
?s
(e.g., only lowercase English letters)?To solve the problem efficiently, we can use the “Expand Around Center” approach. The idea is to consider every possible center of the palindrome (considering both odd-length and even-length centers) and expand outwards to find the longest palindromic substring for each center.
This approach ensures we check all potential palindromic centers and efficiently find the longest one.
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i); // Odd-length palindromes
int len2 = expandAroundCenter(s, i, i + 1); // Even-length palindromes
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}
The time complexity of this approach is O(n^2), where n is the length of the input string. This is because for each character, we expand around the center for potentially all characters (both for odd-length and even-length palindromes).
The space complexity is O(1). No extra space proportional to the input size is used; only a few variables for indexing and calculation are utilized.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?