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

String Palindrome with stack and queue (C++)

本文关键字:回文 c++ 字符串 堆栈 队列      更新时间:2023-10-16

在没有空格的情况下编译得很好,但是一旦我在其中添加了空格,它就会告诉我它不是回文或超时。任何帮助将非常感激!

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());
}

第一行

cin >> the_string;

没有一整行。用这个代替

getline(cin, the_string);

其次,在调试你的算法时打印出大量的信息。例如,如果添加

cout << "You entered: '" << the_string << "'" << endl;

你可以很容易地看到你实际测试的字符串

我得到了这个解决方案工作得很好。

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;
    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;
}
void main()
{
    queue<char> q;
    stack<char> s;
    char letter;
    int mismatches = 0;

    cout << "Enter a word and I will see if it's a palindrome:" << endl;
    cin >> letter;
    q.push(letter);
    s.push(letter);
    int i = 0;
    while (cin.peek() != 'n')
    {
        cin >> letter;
        if (isalpha(letter))
        {
            q.push(letter);
            s.push(letter);
        }
        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;
    }
    cout << endl;
    cout << "Homework done!" << endl;
    cout << "You are Welcome!" << endl;
    system("pause");
}