簡體   English   中英

初學者C ++回文

[英]Beginner c++ palindrome

我需要使用堆棧和隊列來測試回文。 該程序可以很好地解決諸如賽車一詞的問題。 我遇到的問題是我需要忽略空格和標點符號,以便我可以測試句子和問題。 任何幫助表示贊賞。

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

移動

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

到if語句,如下所示:

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

您正在檢查它是否是字母字符,這樣,您甚至都不會在堆棧/隊列中加載非字母字符。 如果要允許使用非字母字符並只過濾掉它們,請考慮使用while(cin >> character)這樣它就不會終止於第一個非字母char上。

您可以做一些簡單的事情,例如:

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

參考: http : //www.cplusplus.com/reference/cctype/isspace/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM