1. 题目

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

2. 思路

查找最长回文子串。
dp算法:
dp[i, j] = dp[i+1, j-1] + 2, if s[i] == s[j];
dp[i, i] = 1
dp[i, i-1] = 0;
迭代求解到最大值,并在过程中记录下起终的下标。

3. 代码

耗时:203ms

class Solution {
public:
    void reset(int len) {
        for (int i = 0 ; i < len; i++) {
            dp[i][i] = true;
            for (int j = i + 1; j < len; j++) {
                dp[i][j] = false;
            }
        }
    }
    
    string longestPalindrome(string s) {
        int len = s.length();
        if (len <= 1) {
            return s;
        }
        reset(len);
        int max = 1;
        int cur = 1;
        int max_i = 0;
        int max_j = 0;
        for (int i = len - 1; i >= 0; i--) {
            for (int j = i + 1; j < len; j++) {
                if (( i+1 >= j-1 || dp[i+1][j-1]) && s[i] == s[j]) {
                    dp[i][j] = true;
                    cur = j - i + 1;
                    if (cur > max) {
                        max = cur;
                        max_i = i;
                        max_j = j;
                    }
                }
            }
        }
        return s.substr(max_i, max_j - max_i + 1);
    }
    
private:
    bool dp[1000][1000];
};

knzeus
72 声望28 粉丝

行万里路,读万卷书