LeetCode -- Longest Palindromic Substring

链接: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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值