递归函数,逐步递进
#include<iostream> #include<cstring> using namespace std; int fun(int low, int high, char *str, int length) { if (length == 0 || length == 1) return 1; if (str[low] != str[high]) return 0; return fun(low+1, high-1, str, length-2); } int main() { char str[1000]; gets(str); int length = strlen(str); //返回1代表是, 0代表不是 cout << fun(0, length-1, str, length) << endl; return 0; }
最大回文子串
#include<stdio.h> #include<string.h> int judge(int low, int high, char *str, int length) { if (length == 0 || length == 1) return 1; if (str[low] != str[high]) return 0; return judge(low+1, high-1, str, length-2); } int main() { int size,i,j,max,f=0; char a[1000]; while(gets(a)) { if(!strcmp(a,"end")) break; size=strlen(a); max=1; for(i=0;i<size;i++) for(j=i+1;j<size;j++) if(judge(i,j,a,j-i+1)) max=(max<j-i+1?j-i+1:max); printf("Case %d: %d ",++f,max); } }