Skip to main content

LeetCode 5: Longest Palindromic Substring in Java

· One min read
Apache Wangye
Software developer and technical writer

Every palindrome has a center. Expand around each character for odd-length palindromes and around each adjacent pair for even-length palindromes.

class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() < 2) return s;

int start = 0;
int end = 0;

for (int i = 0; i < s.length(); i++) {
int odd = expand(s, i, i);
int even = expand(s, i, i + 1);
int len = Math.max(odd, even);

if (len > end - start + 1) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}

return s.substring(start, end + 1);
}

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;
}
}

This approach uses O(n²) time and O(1) extra space. A dynamic-programming solution also takes O(n²) time but requires O(n²) memory. Manacher's algorithm reaches linear time but is substantially more complex.

Page views: --

Total views -- · Visitors --