Back to DSA
Longest Palindromic Substring
mediumFor a given string, find and return the longest substring that reads the same forwards and backwards. If multiple substrings share the maximum length, any one of them is acceptable.
Examples
Example 1:
Input:
s = "racecar"Output:
"racecar"Explanation: The entire string is a palindrome.
Example 2:
Input:
s = "abcda"Output:
"a"Explanation: No multi-character palindromic substring exists, so any single character is valid.
Hints
class Solution {
public String longestPalindrome(String s) {
int start = 0, maxLen = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expand(s, i, i);
int len2 = expand(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > maxLen) {
maxLen = len;
start = i - (len - 1) / 2;
}
}
return s.substring(start, start + maxLen);
}
private int expand(String s, int left, int right) {
while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}
}Time complexity
O(n^2)Space complexity
O(1)