LeetCode-Longest Palindromic Substring

来源:互联网 发布:python swf反编译 编辑:程序博客网 时间:2024/05/29 02:06

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.

Solution:

Code:

<span style="font-size:14px;">class Solution {public:    string longestPalindrome(string s) {        int length = s.size();        if (length == 0 || length == 1)            return s;        string copy;        //construct new string        for (int i = 0; i < length; ++i) {            copy += "#";            copy += s.substr(i, 1);        }        copy += "#";                length = copy.size();        vector<int> radius(length, 0);        int center = 1;        radius[center] = 1;        int maxRadius = 1;        for (int i = 2; i < length; ++i) {            if (i >= center+radius[center]) {                for (int j = 1; i-j >= 0 && i+j < length; ++j)                    if (copy[i-j] == copy[i+j]) ++radius[i];                    else break;                center = i;            } else {                int map = 2*center-i;                if (i+radius[map] < center+radius[center])                    radius[i] = radius[map];                else {                    radius[i] = center+radius[center]-i;                    for (int j = center+radius[center]-i+1; i-j >= 0 && i+j < length; ++j)                        if (copy[i-j] == copy[i+j]) ++radius[i];                        else break;                    center = i;                }            }            maxRadius = radius[maxRadius]>radius[i]?maxRadius:i;        }        return s.substr(maxRadius/2-radius[maxRadius]/2, radius[maxRadius]);    }};</span>


0 0
原创粉丝点击