您的位置:首页 > 其它

LeetCode -- Longest Palindromic Substring

2013-09-05 15:21 246 查看
链接: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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: