回文是指正读反读均相同的字符序列;如“abba”和“abdba”均是回文,但“good”不是回文。试写一个算法判定给定的字符序列是否是回文。(提示:将一半字符入栈)
算法分析:回文的判定关键在于字符串是否是关于中心元素对称的,即将字符串逆序在与原字符串进行比较。由于栈具有先进后出的特点,所以栈是该问题的最佳解决方法,将字符串入栈,然后再进行弹出操作,与原字符串进行比较,相同即为回文。
考虑到待测字符串会有长短的不同,短字符串用上述方法即可,但长字符串会造成时间的浪费,这时就应考虑回文的另一特点:是关于中心元素对称的。所以为了节省时间可以先将一半的字符串入栈然后再出栈与剩下的字符进行比对,当比对结果全部正确时,即为回文,反之则不是。
#include "stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//定义栈
typedef char ElemType;
typedef struct
{
int stack_size;
ElemType *top;
ElemType *base;
}Stack;
enum Status{ ERROR, OK };
Status InitStack(Stack &S, ElemType *t) //初始化栈
{
int len = strlen(t);
S.base = (ElemType *)malloc(len * sizeof(ElemType));
if (S.base == NULL)
return ERROR;
S.top = S.base;
S.stack_size = len;
}
//入栈
Status Push(Stack &S, ElemType e)
{
if (S.top - S.base == S.stack_size)
return ERROR;
*S.top++ = e;
return OK;
}
//出栈
Status Pop(Stack &S, ElemType &e)
{
if (S.top == S.base)
return ERROR;
e = *--S.top;
return OK;
}
//判空
int StackEmpty(Stack S)
{
return (S.top == S.base);
}
Status Panduan(ElemType *t) //判断t[]是否为回文
{
Stack S;
ElemType e;
int i, len;
InitStack(S, t);
len = strlen(t); //求数组长度
for (i = 0; i<len / 2; i++)//将一半字符入栈
Push(S, t[i]);
if (strlen(t) % 2 == 1)
i++;
while (!StackEmpty(S))// 每弹出一个字符与相应字符比较
{
Pop(S, e);
if (e != t[i])
return ERROR;// 不等则返回0
else i++;
}
return OK; // 比较完毕均相等
}
int main()
{
int len = 0;
ElemType *a = NULL;
printf("你要输入几个字符:");
scanf("%d", &len);
getchar(); //吃掉回车
a = (ElemType *)malloc(len * sizeof(ElemType));
printf("\n请输入待检测的字符串:");
gets(a);
if (Panduan(a))
printf("\n是回文字符串");
else
printf("\n不是回文字符串");
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)