【leetcode】5. Longest Palindromic Substring 最长回文子串

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
    原文地址: https://segmentfault.com/a/1190000007273160
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞