用递归的方法,判断某个字符串是否为回文

回文,即一个字符串正读倒读都一样,如abcdcba

递归,就是重复使用同一种方法。

在判断字符串是否是回文的时候,如果要采用递归,首先要分析出重复做的是什么事情

这里很明显,要重复判断两端的字符是不是相等的,直到剩下最后一个或者0个字符的时候

 1 #include "stdafx.h"
 2 #include "stdio.h"
 3 #include "string"
 4 using namespace std;
 5 
 6 int fun(char *ptr,int len)
 7 {
 8     if (len==1||len==0) return 1;
 9     if (ptr[0]==ptr[len-1])
10     {
11         ptr++;
12         fun(ptr,len-2);
13     }
14     else return 0;
15 }
16 
17 
18 
19 
20 int _tmain(int argc, _TCHAR* argv[])
21 {
22     char test[20]={0};
23     printf("please input the test string\n");
24     scanf("%s",test);
25 
26     if (fun(test,strlen(test))) printf("yes! it is\n");
27     else
28         printf("no! it is not\n");
29     return 0;
30 }

递归的运行时间长,占用内存大,好处是代码量短

 

posted @ 2013-05-10 16:27  songnb_7  阅读(1614)  评论(0编辑  收藏  举报