简体   繁体   English

初学者C ++回文

[英]Beginner c++ palindrome

I need to use a stack and queue to test for a palindrome. 我需要使用堆栈和队列来测试回文。 The program works fine with one word answers such as racecar. 该程序可以很好地解决诸如赛车一词的问题。 The problem i am having is that i need to ignore space and punctuation so i can test sentences and questions. 我遇到的问题是我需要忽略空格和标点符号,以便我可以测试句子和问题。 Any help is appreciated. 任何帮助表示赞赏。

#include <iostream>
#include <stack>
#include <queue>
using namespace std;

int main()
{
    bool palindrome = true;
    char character;
    stack<char> stack;
    queue<char> queue;  
    char a;
    char b;

    cout << "Enter a string; press return." << endl;
    cin >> character;


    while (isalpha(character))
    {
        if (isalpha(character))
        {
            character = tolower(character);
        }

        stack.push(character);
        queue.push(character);
        cin.get(character);
    }

    while (!queue.empty())
    {
        a = stack.top();
        b = queue.front();
        stack.pop();
        queue.pop();
        if (a != b)
            palindrome = false;
    }


    if (palindrome)
        cout << "String is a palindrome." << endl;
    else
        cout << "String is not a palindrome." << endl;
    system("pause");
    return 0;
}

Move 移动

stack.push(character);
queue.push(character);

to the if statement, like so: 到if语句,如下所示:

if (isalpha(character))
{
      character = tolower(character);
      stack.push(character);
      queue.push(character);
}

You are checking whether it's an alpha character, this way, you won't even load the non-letter characters in the stack/queue. 您正在检查它是否是字母字符,这样,您甚至都不会在堆栈/队列中加载非字母字符。 If you want to allow using non alpha characters and to just filter them out, consider using while(cin >> character) so it doesn't terminate on the first non-letter char. 如果要允许使用非字母字符并只过滤掉它们,请考虑使用while(cin >> character)这样它就不会终止于第一个非字母char上。

You could do something simple like: 您可以做一些简单的事情,例如:

while (!queue.empty())
{
    While(isspace(stack.top())
    {
        stack.pop();
    }
    While(isspace(queue.front())
    {
        queue.pop();
    }
    a = stack.top();
    b = queue.front();
    stack.pop();
    queue.pop();
    if (a != b)
        palindrome = false;
}

Reference: http://www.cplusplus.com/reference/cctype/isspace/ 参考: http : //www.cplusplus.com/reference/cctype/isspace/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM