您的位置:首页 > 其它

回文字符串的判定------非递归与递归实现(未完)

2014-04-19 07:49 337 查看
检测一个字符串时候具有回文特性,回文特性的字符包括字母(同一字母的大小写等价)和数字,并且可以忽略空格和标点符号。

1.非递归实现

这里非递归实现的思想就是遍历字符串,将字符串strsrc[]的字母和数字赋给另一个字符数组str(目的是为了消除其他标号对判断回文的干扰),然后判断str[]是否是回文,它和源字符串strsrc的回文特性是一致的。

代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 20
void TestPalindrome(const char *strsrc);
int main(void)
{

char *strsrc=(char *)malloc(sizeof(char)*MAX);
printf("input the string you want to test:\n");
gets(strsrc);
TestPalindrome(strsrc);
return 0;
}

void TestPalindrome(const char *strsrc)
{
char *p1=(char *)malloc(sizeof(char)*MAX);
char *str=(char *)malloc(sizeof(char)*MAX);
int j,i=0;
if(NULL==p1 || NULL==str)
{
printf("insufficient memory!\n");
exit(0);
}
strcpy(p1,strsrc);
while(*p1 !='\0')
{
if(*p1>='A' && *p1<='Z')//'A'~'Z'---->'a'~'z'
*p1=*p1+'a'-'A';
if((*p1>='a' && *p1<='z') || (*p1>='0' && *p1<='9'))
{
str[i]=*p1;//将源字符串的字母和数字赋给字符串数组src[]
i++;
}
p1++;
}
for(j=0;j<i/2;j++)
{
if(str[j] !=str[i-j-1])
break;
}
if(j>=i/2)
printf("该字符串为回文序列!\n");
else
printf("该字符串不是回文序列!\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: