c++ - 具有堆栈和队列的字符串回文 (C++)

标签 c++

这可以很好地编译并且在没有空格的情况下也能正常工作,但是一旦我在其中放入空格就会告诉我它不是回文或超时。任何帮助将不胜感激!

int main( )
{
   queue<char> q;
   stack<char> s;
   string the_string;
   int mismatches = 0;
   cout << "Enter a line and I will see if it's a palindrome:" << endl;
   cin  >> the_string;

   int i = 0;
   while (cin.peek() != '\n')
   {
       cin >> the_string[i];
       if (isalpha(the_string[i]))
       {
          q.push(toupper(the_string[i]));
          s.push(toupper(the_string[i]));
       }
       i++;
   }

   while ((!q.empty()) && (!s.empty()))
   {
      if (q.front() != s.top())
          ++mismatches;

        q.pop();
        s.pop();
   }

   if (mismatches == 0)
       cout << "This is a palindrome" << endl;
   else
       cout << "This is not a palindrome" << endl;

   system("pause");
   return EXIT_SUCCESS;
}

最佳答案

为什么这么复杂?

你可以简单地做:

#include <string>
#include <algorithm>

bool is_palindrome(std::string const& s)
{
  return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}

关于c++ - 具有堆栈和队列的字符串回文 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15595172/

相关文章:

c++ - 使用计数器数组从文件中提取整数并计算响应数?

c++ - 字段声明为 void/struct 或未在此范围内声明的变量

c++ - 只允许从 0 到 1 的数字

c++ - 将按钮连接到任意函数

c++ - 如何使用虚拟访问在 C++ 类中存储常量二维数组?

c++ - 我是否需要使用继承对象(相对于基础对象)来覆盖我的虚函数?

c++ - std::enable_if 跨编译器的不同行为(取决于外部类模板参数)

c++ - 在 C++ 中加速大文件写入磁盘

c++ - 链接到 Xcode 中的库 - 静态或动态

c++ - 与显式初始化相比,了解 C++ 中的复制初始化