括号匹配
#include<iostream>
#include<string>
#include<stack>
using namespace std;
string st;
bool isLeft(char c)
{
if(c=='('||c=='{'||c=='[') return true;
else return false;
}
bool isSame(char c1,char c2)
{
if(c1=='('&&c2!=')') return false;
if(c1=='{'&&c2!='}') return false;
if(c1=='['&&c2!=']') return false;
return true;
}
bool isValid(string s)
{
stack<char> b;
for(int i =0;i<s.length();i++)
{
if( isLeft(s[i]) ) b.push(s[i]);
else
{
if(b.size()==0) return false;
char top = b.top();
if(!isSame(top,s[i])) return false;
else
b.pop();
}
}
if(b.size()==0) return true;
else return false;
}
int main(){
cin>>st;
if(isValid(st))
cout<<"bracket is valid"<<endl;
else
cout<<"bracket is not valid"<<endl;
return 0;
}
|