Home LeetCode. 5. Longest Palindromic Substring
Post
Cancel

LeetCode. 5. Longest Palindromic Substring

[Link] https://leetcode.com/problems/longest-palindromic-substring/

Approach

Every palindrome has either a character at its center (an odd-length palindrome) or a gap between two characters at its center (an even-length palindrome). For each index, expand outward from both kinds of centers while the characters match. Each expansion checks all palindromes with that center.

Keep the best answer as a half-open interval [bestStart, bestEnd). When a longer palindrome is found, replace the interval; otherwise leave it unchanged so an existing maximum-length answer is preserved. An empty string has no centers and returns the empty substring.

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution {
    public String longestPalindrome(String s) {
        int bestStart = 0;
        int bestEnd = 0;

        for (int center = 0; center < s.length(); center++) {
            int left = center;
            int right = center;
            while (left >= 0 && right < s.length()
                    && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            if (right - left - 1 > bestEnd - bestStart) {
                bestStart = left + 1;
                bestEnd = right;
            }

            left = center;
            right = center + 1;
            while (left >= 0 && right < s.length()
                    && s.charAt(left) == s.charAt(right)) {
                left--;
                right++;
            }
            if (right - left - 1 > bestEnd - bestStart) {
                bestStart = left + 1;
                bestEnd = right;
            }
        }

        return s.substring(bestStart, bestEnd);
    }
}

For each of the N positions, two expansions can each inspect up to N characters, so the time complexity is O(N²). The indices use only constant extra space, giving O(1) extra space.

This post is licensed under CC BY 4.0 by the author.

Buy me a coffee