4

这编译得很好,没有空格也能很好地工作,但是一旦我把空格放进去,要么告诉我它不是回文,要么超时。任何帮助将不胜感激!

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;
}
4

4 回答 4

1

首先是线

cin >> the_string;

没有得到一整行。改用这个

getline(cin, the_string);

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

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

您可以轻松查看您实际测试的字符串。

于 2013-03-24T04:46:20.890 回答
1

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

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;
}
于 2013-03-24T06:16:33.013 回答
1

为什么这么复杂?

你可以简单地做:

#include <string>
#include <algorithm>

bool is_palindrome(std::string const& s)
{
  return std::equal(s.begin(), s.begin()+s.length()/2, s.rbegin());
}
于 2013-03-24T04:35:51.593 回答
-1
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");

}
于 2015-11-12T03:11:06.450 回答