題目:設計一個算法,判斷用戶輸入的表達式中是否是迴文(迴文即左右對稱的字符串)。
思路:這道題與判斷表達式括號是否匹配類似,可使用順序棧來解決,區別是迴文要求每個字符都要求匹配,因此將字符串全部入棧,再全部出棧,將最後一個字符與第一個字符比較是否相同,依次比較,若全部相同則爲迴文。
代碼:
#include<iostream>
#include<string>
using namespace std;
#define MaxSize 20
//字符串棧
class Stack
{
char *data;
int top;
public:
Stack();
~Stack();
bool IsEmpty();
bool Push(char e);
bool Pop(char& e);
};
Stack::Stack()
{
data = new char[MaxSize];
top = -1;
}
Stack::~Stack()
{
delete [] data;
}
bool Stack::IsEmpty()
{
return (top == -1);
}
bool Stack::Push(char e)
{
if(top == MaxSize-1) return false; //棧滿
top++;
data[top] = e;
return true;
}
bool Stack::Pop(char& e)
{
if(top == -1) return false; //棧空
e = data[top];
top--;
return true;
}
//判斷迴文
bool IsPalindrome(char str[],int n)
{
int i=0;char e;
Stack st;
while(i<n)
{
st.Push(str[i]);
i++;
}
i=0;
while(i<n)
{
st.Pop(e);
if(str[i]!=e) return false;
i++;
}
return true;
}
void main()
{
cout<<"請輸入表達式:"<<endl;
char str[MaxSize];
cin>>str;
int n = strlen(str);
if(IsPalindrome(str,n))
cout<<"表達式"<<str<<"是迴文"<<endl;
else
cout<<"表達式"<<str<<"不是迴文"<<endl;
}
測試數據1:qwerewq
測試結果1:
測試數據2:qwertyu
測試結果2: