LeetCode -- Longest Palindromic Substring

来源:互联网 发布:电脑回收站数据恢复 编辑:程序博客网 时间:2024/05/06 21:17

链接:http://leetcode.com/onlinejudge#question_5

原题:

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.

思路:之前,我都是用O(n^2)做的,这回尝试一下用O(n)时间做一下,当然,方法是别人想出来的,呵呵。

请参考:http://www.felix021.com/blog/read.php?2040

真是算法无止境啊,这碗水很深。


代码:

class Solution {public:    string longestPalindrome(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (s.size() == 0)            return "";                string str = "#";        for (int i=0; i<s.size(); i++) {            str.append(1, s[i]);            str.append(1, '#');        }                vector<int> state(str.size());        state[0] = 1;        int center = 0;        int rBorder = center + state[0];                for (int i=1; i<str.size(); i++) {            int j = 2 * center - i;            if (j < 0) {                state[i] = 1;                int n = 1;                while (i-n >= 0 && i+n < str.size() && str[i-n] == str[i+n])                    n++;                state[i] += n - 1;            } else {                if (rBorder - i > state[j])                    state[i] = state[j];                else {                    state[i] = rBorder - i;                    int n = rBorder - i;                    while (i-n >= 0 && i+n < str.size() && str[i-n] == str[i+n]) {                        n++;                        state[i]++;                    }                }            }                        if (i + state[i] > rBorder) {                rBorder = i + state[i];                center = i;            }        }                int maxLength = 1;        int maxCenter = 0;        for (int i=0; i<state.size(); i++) {            if (state[i] > maxLength) {                maxLength = state[i];                maxCenter = i;            }        }                maxLength;        string palindrome = "";        for (int i=maxCenter-maxLength+1; i<maxCenter+maxLength; i++) {            if (str[i] != '#')                palindrome += str[i];        }                return palindrome;    }};


原创粉丝点击