[C#] C#利用堆栈进行回文检测 →→→→→进入此内容的聊天室

来自 , 2020-11-14, 写在 C#, 查看 118 次.
URL http://www.code666.cn/view/7c0f63c1
  1. // ------------------算法二:利用栈先进后出,队列先进先出的特点----------------
  2. //abba
  3. Console.WriteLine("算法2:请输入一个字符串!");
  4. //调用.net里面自带的Queue,Stack,并初始化
  5. Queue<char> queue = new Queue<char>();
  6. Stack<char> stack = new Stack<char>();
  7. string str2 = Console.ReadLine(); //获取输入字符
  8. for (int i = 0; i < str2.Length; ++i) //放入栈和队列
  9. {
  10.   queue.Enqueue(str2[i]);
  11.   stack.Push(str2[i]);
  12. }
  13.  
  14. IsHuiWen(queue, stack);
  15.  
  16.  
  17.  
  18. //检验函数,只需要检验1/2的位置,因为只需要检测前半部分和后半部分是否相同。
  19. static void IsHuiWen(Queue<char> queue, Stack<char> stack)
  20. {//aabb /abbaa
  21. //abcd
  22. // abbba
  23.   int i = 0, total = 0;
  24.   bool isHuiWen = true;
  25. //确定所要取出的字数,分奇数偶数两种情况
  26.   if (queue.Count % 2 == 0)
  27.   total = queue.Count / 2;
  28.   else
  29.   total = queue.Count / 2 + 1;
  30. //通过循环比对出栈元素和出队元素是否相同
  31.   while (queue.Count != 0 && stack.Count != 0)
  32.   {
  33.     if (queue.Dequeue() != stack.Pop()) //不相等
  34.     {
  35.     isHuiWen = false;
  36.     break;
  37.     }
  38.     else if (i == total) //检查到一半时,跳出循环
  39.       break;
  40.     ++i;
  41.   }
  42.  
  43. if (!isHuiWen)
  44.   Console.WriteLine("这不是回文");
  45. else
  46.   Console.WriteLine("这是回文");
  47. }
  48. //csharp/7217

回复 "C#利用堆栈进行回文检测"

这儿你可以回复上面这条便签

captcha