今天笔试,遇到一道判断字符串是否是回文的题。什么是回文?回文是正读和反读都一样的字符串,如下列字符串“radar" "eye"都是回文串。
一个简单的回文程序如下:
在VC6.0用C写的:
#include<stdio.h>int hw(char *s);//验证回文数int main(){ char s[10]; printf("请输入字符串\n"); gets(s); if(hw(s))printf("%s属于回文串\n",s); else printf("%s不属于回文串\n",s); return 0;}
int hw(char *s){ char *p1=s,*p2; p2=s+strlen(s)-1; while(p1<p2) if(*(p1++)!=*(p2--))return 0; return 1; }
如果用 .net里面自带的Queue,Stack,他们都是泛型类型,可以用下面这种思路:
Queue<char> queue = new Queue<char>();
Stack<char> stack = new Stack<char>();
string str = Console.ReadLine(); //获取输入字符
for (int i = 0; i < str.Length; ++i) //放入栈和队列
{
queue.Enqueue(str[i]);
stack.Push(str[i]);
}
检验函数,只需要检验1/2的位置,因为只需要检测前半部分和后半部分是否相同。
static void IsHuiString(Queue<char> queue, Stack<char> stack)
{
int i = 0,total=0;
bool isHui = true;
if (queue.Count % 2 == 0)
total = queue.Count / 2;
else
total = queue.Count / 2 + 1;
while (queue.Count != 0 && stack.Count != 0)
{
if (queue.Dequeue() != stack.Pop()) //不相等
{
isHui = false;
break;
}
else if (i == total) //已经检查了一半
break;
++i;
}
if(!isHui)
Console.WriteLine("This is not Hui Word!");
else
Console.WriteLine("This is Hui Word!");
参考:http://www.cnblogs.com/tobemvp/archive/2010/08/18/1802547.html