5. Longest Palindromic Substring

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.

Example 1:

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"
Output: "bb"

把input string裡每個char位置都當作一個palindrome中心點往左右擴張看是否能形成palindrome,要考慮形成的palindrome長度為奇數和偶數的情形。

// Expand from the center
string longestPalindrome(string s) { // time: O(n^2); space: O(1)
    int n = s.size(), start = 0, max_len = 0;
    if (n < 2) return s;
    for (int i = 0; i < n; ++i) {
        helper(s, i, i, start, max_len); // odd length
        helper(s, i, i + 1, start, max_len); // even length
    }
    return s.substr(start, max_len);
}
void helper(string& s, int l, int r, int& start, int& max_len) {
    while (l >= 0 && r < s.size() && s[l] == s[r]) {
        --l, ++r;
    }
    if (max_len < r - l - 1) {
        max_len = r - l - 1;
        start = l + 1;
    }
    return;
}

利用Dynamic programming的概念搭配一個2D vector掃描所有可能的palindrome組合,dp[i][j]代表string[i...j]是否為palindrome。 (i) dp[i][j] = true if i == j (ii) dp[i][j] = s[i] == s[j] if j = i + 1 (iii) dp[i][j] = s[i] == s[j] && dp[i + 1][j - 1] if j > i + 1

Manacher演算法能達到O(n) time complexity。

Last updated

Was this helpful?