实现代码
对于不同种类的括号同样适用
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<stack>
using namespace std;
bool paren(char *s,int lo,int hi)
{
stack<char> pi;
for(int i=lo;i<hi;i++){
if(s[i]=='(') pi.push(s[i]); //遇到左括号是进栈
else if(!pi.empty()) pi.pop(); //遇到右括号,若非空,则弹出左括号
else return false; //遇到右括号时并且栈为空,此时不匹配,返回false不必在匹配了
}
return pi.empty(); // 仅当栈空时匹配
}
int main()
{
char s[50];
scanf("%s",s);
if(paren(s,0,strlen(s)))
cout<<"匹配"<<endl;
else
cout<<"不匹配"<<endl;
}
但只有一种括号是,也可直接用数字记录,仅当最后的数字为0括号才匹配(如上图).但是这种情况只试用于一种类型的括号,如果有多种类型的括号时这种方法就不能用了,而栈依然可以。
其实只有这种"括号"类型,不一定知道它的类型和数目,依然可以用栈来解决。