2018/2/18
算法
1.回文是什么?
回文是一个从首到尾或者从尾到首都一样的字符串,如abcba等;
2.怎样判断一个字符串是回文
核心方法:栈
找到字符串的中点,把从首位到中点的字符串归于栈中,然后和中点到末尾的字符串一一比较,如果吻合就是回文(注意奇数偶数的判断)
/*判断一个字符串是否是回文*/
/*1.先获得一个字符串
2.再获取字符串的中点
3.把中点以前的量入栈
4.再和中点以后的量对比*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char a[101], s[101];
int top, next,len,mid,i;
printf("请输入字符串\n");
gets(a);//获得字符串
len = strlen(a);//获得字符串的长度
mid = len / 2 - 1;//判断字符串的中点
/*入栈操作*/
for (i = 0; i <= mid; i++)
{
top = 0;
top++;
s[top] = a[i];
//s[++top]=a[i];
}
/*判断奇偶*/
if (len % 2 == 0)
{
next = mid + 1;
}
else
{
next = mid + 2;
}
//开始后半段操作,出栈和后来的比较
for (i = next; i < len; i++)
{
if (a[i] != s[top])
break;
top--;
}
if (top == 0)//一一匹配为回文
printf("该字符串为回文");
else
printf("该字符串不为回文");
system("pause");
}