Longest Palindromic Substring

来源:互联网 发布:excel中数据合并计算 编辑:程序博客网 时间:2024/06/05 18:07

简单的动态规划,一个子串两头相等的话,它是不是回文的就取决与掐掉两头后剩下的部分是不是回文的。

网上有O(n)的解法,不过等我有时间了再看吧。

class Solution {public:    bool DP[1001][1001];    string longestPalindrome(string s) {        memset(DP, false, sizeof(DP));        for (int i = 0; i < s.length(); ++i)            DP[i][i] = true;        int start, end;        for (int len = 2; len <= s.length(); ++len) {            for (int i = 0; len + i - 1 < s.length(); ++i) {                int j = len + i - 1;                if (s[i] != s[j])                    DP[i][j] = false;                else {                    if (j == i + 1)                        DP[i][j] = true;                    else                        DP[i][j] = DP[i + 1][j - 1];                    if (DP[i][j]) {                        start = i;                        end = j;                    }                }            }        }        return s.substr(start, end - start + 1);    }};

http://oj.leetcode.com/problems/longest-palindromic-substring/

0 0