题目:设计一个算法,判断用户输入的表达式中括号是否匹配,表达式中可能含有圆括号、中括号和大括号。
思路:建立一个顺序栈,当表达式中有左括号时将其入栈,当出现右括号时,将栈顶元素出栈,检查与当前右括号是否匹配。最后如果栈为空则表示该表达式中的括号是匹配的。
代码:
#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 IsMatch(char str[],int n)
{
int i=0;
char e;
Stack st; //建立顺序栈
while(i<n)
{
if(str[i] == ‘(‘ || str[i] == ‘[‘ || str[i] == ‘{‘)
st.Push(str[i]);
else
{
if(str[i] == ‘)‘)
{
if(!st.Pop(e)) return false;
if(e!=‘(‘) return false;
}
if(str[i] == ‘]‘)
{
if(!st.Pop(e)) return false;
if(e!=‘[‘) return false;
}
if(str[i] == ‘}‘)
{
if(!st.Pop(e)) return false;
if(e!=‘{‘) return false;
}
}
i++;
}
if(st.IsEmpty()) return true;
else return false; //遍历字符串后栈不为空说明有不匹配字符
}
void main()
{
cout<<"请输入表达式:"<<endl;
char str[] = "";
cin>>str;
int n = strlen(str);
if(IsMatch(str,n))
cout<<"表达式"<<str<<"中的括号是匹配的"<<endl;
else
cout<<"表达式"<<str<<"中的括号是不匹配的"<<endl;
}
测试数据1:9*{8+[7-(6+5)]}
测试结果1:
测试数据2:[[[[[)]]]]]
测试结果2:
原文地址:http://blog.csdn.net/u011421608/article/details/46381569