0

スタックとキューを使用して、特定の単語が回文であるかどうかを確認します。新しいキャラクターをスタックにプッシュできますが、複数のキャラクターをキューにプッシュすることはできません。コードのどこが間違っているのかわかりません。どんな助けでも大歓迎です。以下は、Dev-C++ を使用した C++ のコードです。御時間ありがとうございます!

#include <iostream>
#include <stack>
#include <queue>
#include <string>

using namespace std;

void push_char()
{

  string givenword; int sizeword, countchar;
  string letter;
  stack<string> stackword; string stawo1;
  queue<string>  queueword; string quewo1;

  cout<<"enter the word to test "<<endl;
  getline(cin,givenword);
  string str (givenword);
  sizeword=str.size();
  cout<<" the word given   "<<givenword<<"   size of word= "<<sizeword  <<endl;
  countchar=0;
  bool pali=true;

  while ((countchar<sizeword))
  {          
    stackword.push(str.substr(countchar,1));
    queueword.push(str.substr(countchar,1));
    cout<<" stack letter= "<<stackword.top()<<" queue letter= "<<queueword.front()<<endl;
    countchar++;

    if(stackword.top()==queueword.front())
      cout<<"same letter found !"<<endl;
    else
      pali=false;

    if (pali==false)
      cout<<"not a palindrome"<<endl;
    else
      cout<<"palindrome!"<<endl;
  }
}

int main()
{
  push_char();
}
4

3 に答える 3

0

ここには2つのオプションがあります。1つ目は、aleph_nullが提案するものです。最初のパスで文字をコンテナに追加し、2番目のパスでそれらを比較するダブルパスです。2番目のオプションは、あなたと同じようにそれらを比較することですが、単語の両端を見てください。これには実際にはコンテナは必要ありませんが、最小限の変更でwhileループのコードは次のようになります。

while ((countchar<sizeword))
{          
  stackword.push(str.substr(countchar,1));
  queueword.push(str.substr(sizeword - 1 - countchar,1)); // adding from the back
  cout<<" stack letter= "<<stackword.top();
  cout<<" queue letter= "<<queueword.back()<<endl; // .back() not .front()
  countchar++;

  if(stackword.top()==queueword.back()) // again, looking at the last added char
    cout<<"same letter found !"<<endl;
  else
    pali=false;

  // as Joe McGrath pointed out this should probably be outside the loop...
  if (pali==false)
    cout<<"not a palindrome"<<endl;
  else
    cout<<"palindrome!"<<endl;
}

お役に立てば幸いです。

ローマ人

于 2011-11-03T16:06:24.810 に答える
0

参考までに、 str.substr(countchar,

いくつかのポイント:

1)あなたのコードは問題ありませんが、アルゴリズムはそうではありません。一枚の紙をつかみ、あなたがしていることを一歩踏み出してください。

2) 私はあなたが何をしようとしているのか分かります...次のようなテストされていないコードですよね?

for(int i=0; i<sizeword; ++i) {
  stackword.push(str[i]);
  queueword.push(str[i]);
}

pali = true;
for(int i=0; i<sizeword; ++i) {
  if(stackword.top() != queueword.front()) {
    pali = false;
    break;
  }
  stackword.pop();
  queueword.pop();
}
于 2011-11-02T04:26:51.653 に答える
0

回文を見つけるためのより良い方法があります...しかし、それはあなたが尋ねた質問ではありません.

この行で: if(stackword.top()==queueword.front())

あなたのエラーがある場所です。キューにプッシュするときは、キューの最後にプッシュします。フロントは変わりません。したがって、あなたには、そこにあるものは 1 つしかないように見えます。

スタックにプッシュすると、既存のスタックの上にプッシュされます。

于 2011-11-02T04:11:28.377 に答える