http://blog.youkuaiyun.com/hopeztm/article/details/7932245
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.
class Solution {
public:
string longestPalindrome(string ss) {
string s = preProcess(ss);
int c=0, r=0;
int* p = new int[s.length()];
p[0] = 0;
p[s.length()-1] = 0;
for(int i=1;i<s.length()-1;++i){
int mirror = c - (i-c);
p[i] = (r>i)?min(r-i, p[mirror]):0; //如果r没覆盖到i,赋值为0
while(s[i+p[i]+1] == s[i-p[i]-1]){
p[i]++;
}
if(i+p[i]>r){
r = i+p[i];
c = i;
}
}
int maxLen = 0;
int center = 0;
for(int i=1;i<s.length()-1;++i){
if(p[i] > maxLen){
maxLen = p[i];
center = i;
}
}
delete[] p;
return ss.substr((center-1-maxLen)/2, maxLen); //去掉第一个^,然后去掉maxLen到大构造string的位置,然后除于2得到原始string的位置
}
string preProcess(string s){
if(s.length() == 0){
return "^$";
}
string res = "^";
for(int i=0;i<s.length();++i){
res += "#" + s.substr(i, 1); //注意这里用substr得到新的string,作用域问题,用[]是不行的!
}
res += "#$";
return res;
}
};
本文介绍了一种高效算法来找到给定字符串中的最长回文子串。通过预处理字符串并利用中心扩展的方法,该算法能在O(n)的时间复杂度内解决问题。文中详细解释了如何进行预处理以及如何确定回文子串的中心。
3925

被折叠的 条评论
为什么被折叠?



