【发布时间】:2020-07-23 23:40:10
【问题描述】:
问题:回文是向前和向后读取相同的字符串,例如,radar、toot 和 madam。接下来的挑战是编写一个算法,从左到右逐字读取一个句子,并确定它是否是回文。 以回文串为例。
- “女士,我是亚当。”
- “夏娃”
解决这个问题的算法比较简单,
- 使用堆栈和队列。
- 将令牌(单词)推送和入队到两种数据结构中。
- 弹出和出列标记(单词)并进行比较。
- 执行删除操作,直到其中一个数据结构为空。如果情况是两者都是空的,则该句子是回文。
你的任务是判断用户输入的字符串是否是回文。
#include<iostream>
#include<string>
#include<stack>
#include<queue>
using namespace std;
#define MAX 1000
class Stack
{
int top;
public:
string myStack[MAX];
Stack() { top = -1; }
bool push(string item)
{
if (top >= (MAX - 1)) {
cout << "Stack is full";
return false;
}
else {
myStack[++top] = item;
cout << item << endl;
return true;
}
}
string pop()
{
if (top < 0) {
cout << "Stack Underflow!!";
return 0;
}
else {
string item = myStack[top--];
return item;
}
}
bool isEmpty()
{
if (top == -1)
return true;
else
return false;
}
};
class Queue
{ public:
string myqueue[MAX];
int front, rear;
Queue()
{
front = -1;
rear = -1;
}
bool isFull() {
if (front == 0 && rear == MAX - 1) {
return true;
}
return false;
}
bool isEmpty() {
if (front == -1)
return true;
else
return false;
}
void enQueue(string item) {
if (isFull()) {
cout << endl << "Queue is full!!";
}
else {
if (front == -1) front = 0;
rear++;
myqueue[rear] = item;
cout << item << " "<<endl;
}
}
string deQueue() {
string value;
if (isEmpty()) {
cout << "Queue is empty!!" << endl;
return false;
}
else {
value = myqueue[front];
if (front >= rear)
{
front = -1;
rear = -1;
}
else {
front++;
}
return(value);
}
}
};
int main()
{
bool palindrome = true;
Stack stack;
stack.push("m");
stack.push("a");
stack.push("d");
stack.push("a");
stack.push("m");
Queue queue;
queue.enQueue("m");
queue.enQueue("a");
queue.enQueue("d");
queue.enQueue("a");
queue.enQueue("m");
while (sizeof stack == 0 || sizeof queue == 0 )
{
stack.pop();
queue.deQueue();
};
if (sizeof stack == sizeof queue )
{
cout << "The given word is palindrome." << endl;
}
else
{
cout << "The given word is not a palindrome." << endl;
}
system("pause");
return 0;
}
【问题讨论】:
-
这个完全相同的分配是另一个用户asked about yesterday。必须是同学。
-
请解释具体是什么不起作用以及您如何尝试解决这个问题。
-
我不明白如何在比较堆栈和队列中的项目时同时弹出和双端队列。
标签: c++ data-structures stack queue