LeetCode OJ - Longest Palindromic Substring

来源:互联网 发布:空巢老人调查数据 编辑:程序博客网 时间:2024/05/20 18:50

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.

分析:动态规划,简单题。在i位置要求出所有的回文情况,值需要知道 i 到 n 之前的所有回文情况即可。二位迭代即可以解决。

当 i = j, dp[i][i] = true;

当i = j - 1, dp[i][j] = (s[i] == s[i]) ? true : false;

当i = j - 2, dp[i][j] = (s[i] == s[j] && dp[i+1][j-1]) ? true : false;

class Solution {public:    string longestPalindrome(string s) {        int len = s.size();        if(len == 0) return s;                string ret;        bool dp[1000][1000];        for(int i = len - 1; i >= 0; i--) {            for(int j = i; j < len; j++) {                dp[i][j] = false;                }        }                for(int i = len - 1; i >= 0; i--) {            for(int j = i; j < len; j++) {                if(s[i] == s[j]  && (j - i < 2 || dp[i+1][j-1])) {                    dp[i][j] = true;                    if(ret.size() < j - i + 1) {                        ret = s.substr(i, j - i + 1);                    }                }            }        }        return ret;    }};


0 0