[LeetCode] Longest Palindromic Substring - O(n)

#include <string>
#include <vector>
using namespace std;

class Solution {
public:
    string longestPalindrome(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        string str = "#";
        
        for (int i = 0; i < s.size(); i++) {
            str += s[i];
            str += "#";
        }
        
        vector<int> dp(str.size());
        
        int mx = 0;
        int id = 0;
        
        for (int i = 0; i < str.size(); i++) {
            if (mx > i) {
                dp[i] = min(dp[2 * id - i], mx - i);
            } else {
                dp[i] = 1;
            }
            
            int len = dp[i];
            while (str[i - len] == str[i + len])
                len++;
            
            len--;
            dp[i] = len;
            
            if (i + len > mx) {
                mx = i + len;
                id = i;
            }
        }
        
        int ret = 0;
        int pos = 0;
        for (int i = 0; i < dp.size(); i++) {
            if (dp[i] > ret) {
                ret = dp[i];
                pos = i;
            }
        }
        
        return s.substr((pos - ret) / 2, ret);
    }
};

Small Case: 0ms

Large Case: 24ms

Time: O(n)

Space: O(n)

点赞