字符串长度不是很长:
九度OJ题目:click here~~
动态规划就可A
AC_CODE
const int maxn = 108 ;
int solve(string s){
int n = s.size() ;
bool table[maxn][maxn] = {false} ;
int i , j , len , maxlen ;
for(i = 0;i < n ;i++){
table[i][i] = true ;
maxlen = 1 ;
}
for(i = 0;i < n -1 ;i++){
if(s[i] == s[i + 1]) {
table[i][i+1] = true ;
maxlen = 2 ;
}
}
for(len = 3;len <= n;len++){
for(i = 0;i < n -len + 1;i++){
j = i + len - 1 ;
if(s[i] == s[j] && table[i+1][j-1]) {
table[i][j] = true ;
maxlen = len ;
}
}
}
return maxlen ;
}
int main(){
string s ;
while(cin >> s){
cout << solve(s) << endl ;
}
return 0 ;
}
字符串长度很长:
九度OJ题目:click here~~
Manacher算法,线性
这两篇博客介绍了Manacher算法,说的很好,看了就明白~
http://blog.csdn.net/ggggiqnypgjg/article/details/6645824
http://www.felix021.com/blog/read.php?2040
AC_CODE
const int maxn = 200002 ;
int solve(char s[]){
int p[2*maxn] , i , j , id = 0, mx = 0;
memset(p , 0 , sizeof(p)) ;
for(int i = 1;s[i] != '\0';i++){
p[i] = (mx > i ? min(p[2*id - i] , mx - i) : 1) ;
while(s[i - p[i]] == s[i + p[i]]) p[i]++ ;
if(mx < i + p[i]){
mx = i + p[i] ;
id = i ;
}
}
return *max_element(p , p + strlen(s)) - 1;
}
int main(){
int i , j , k ;
char s[maxn] ;
while(scanf("%s",s) != EOF){
int t = 0 ;
int n = strlen(s) ;
char ss[2*n + 8] ;
ss[t++] = '$' ;
for(i = 0; s[i] != '\0';i++){
ss[t++] = '#' ;
ss[t++] = s[i] ;
}
ss[t++] = '#' ;
ss[t] = '\0' ;
cout << solve(ss) << endl ;
}
return 0 ;
}