改进的代码 (输入字符串为s):
int getLongestPalindrome(string s) {
string str;
str.push_back(‘&‘);
for (char item : s) {
str.push_back(‘#‘);
str.push_back(item);
}
str.push_back(‘#‘);
str.push_back(‘$‘);
int pos = 0;
vector<int> len(str.size(), 0);
for (int i = 0; i < str.size(); i++) {
if (i <= pos+len[pos])
len[i] = min(len[2*pos-i], pos+len[pos]-i);
while (str[i-len[i]-1] == str[i+len[i]+1] )
len[i]++;
if (i+len[i] > pos+len[pos])
pos = i;
}
return *(max_element(len.begin(), len.end()));
}
Reference:
[1] http://blog.csdn.net/dyx404514/article/details/42061017
时间: 2024-11-10 17:58:43