Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
#include<iostream>
#include<stack>
#include<cstring>
using namespace std;
bool isValid(string s) {
bool isValid=true;
if(s=="")
return true;
stack<char> nodes;
for(int i=0; i<s.length(); i++){
if(s[i]=='{'||s[i]=='['||s[i]=='('){
nodes.push(s[i]);
}
if(s[i]=='}'){
if(nodes.empty())
return false;
char left=nodes.top();
if(left=='{')
nodes.pop();
else
return false;
}
else if(s[i]==']'){
if(nodes.empty())
return false;
char left=nodes.top();
if(left=='[')
nodes.pop();
else
return false;
}
else if(s[i]==')'){
if(nodes.empty())
return false;
char left=nodes.top();
if(left=='(')
nodes.pop();
else
return false;
}
}
if(nodes.empty())
return true;
else
return false;
}
int main(){
string str;
cin>>str;
cout<<isValid(str)<<endl;
return 0;
}