用栈和队列判断输入字符串是否是回文(回文具有两边对称的性质)

栈是一种先进后出的数据结构,队列是先进先出的结构。对于测试一个字符串是否是回文的问题,其实也就是判断一个字符串两边是否对称的问题。最常见的做法也就是把这个作为一个数组考虑,判断array[i]是否等于array[length-i-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!");
}

调用函数:

IsHuiString(queue, stack);

 

结束!

posted @ 2010-08-18 16:08  Nick Song  阅读(8082)  评论(0编辑  收藏  举报