#include <bits/stdc++.h>
using namespace std;
int isMatching(stack<char> &stk, char c){
if(stk.empty()){
return 0;
}
char topC = stk.top();
if( (topC == '(' && c == ')') || (topC == '{' && c == '}') || (topC == '[' && c == ']') )
return 1;
return 0;
}
bool isValid(string s) {
stack<char> stk;
int len = s.length();
for(int i = 0; i < len; i++){
if(s[i] == '(' || s[i] == '{' || s[i] == '['){
stk.push(s[i]);
continue;
} else if((s[i] == ')' || s[i] == '}' || s[i] == ']') && isMatching(stk, s[i])){
stk.pop();
continue;
}
return false;
}
if(!stk.empty())
return false;
return true;
}
int main() {
cout << isValid("(){}[]") << endl;
cout << isValid("(){(}[]") << endl;
return 0;
}
I2luY2x1ZGUgPGJpdHMvc3RkYysrLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgaXNNYXRjaGluZyhzdGFjazxjaGFyPiAmc3RrLCBjaGFyIGMpewogICAgaWYoc3RrLmVtcHR5KCkpewogICAgICAgIHJldHVybiAwOwogICAgfQogICAgY2hhciB0b3BDID0gc3RrLnRvcCgpOwogICAgaWYoICh0b3BDID09ICcoJyAmJiBjID09ICcpJykgfHwgKHRvcEMgPT0gJ3snICYmIGMgPT0gJ30nKSB8fCAodG9wQyA9PSAnWycgJiYgYyA9PSAnXScpICkKICAgICAgICByZXR1cm4gMTsKICAgIHJldHVybiAwOwp9Cgpib29sIGlzVmFsaWQoc3RyaW5nIHMpIHsKICAgIHN0YWNrPGNoYXI+IHN0azsKICAgIGludCBsZW4gPSBzLmxlbmd0aCgpOwogICAgZm9yKGludCBpID0gMDsgaSA8IGxlbjsgaSsrKXsKICAgICAgICBpZihzW2ldID09ICcoJyB8fCBzW2ldID09ICd7JyB8fCBzW2ldID09ICdbJyl7CiAgICAgICAgICAgICAgICBzdGsucHVzaChzW2ldKTsKICAgICAgICAgICAgICAgIGNvbnRpbnVlOwogICAgICAgIH0gZWxzZSBpZigoc1tpXSA9PSAnKScgfHwgc1tpXSA9PSAnfScgfHwgc1tpXSA9PSAnXScpICYmIGlzTWF0Y2hpbmcoc3RrLCBzW2ldKSl7CiAgICAgICAgICAgIHN0ay5wb3AoKTsKICAgICAgICAgICAgY29udGludWU7CiAgICAgICAgfQogICAgICAgIHJldHVybiBmYWxzZTsKICAgIH0KICAgIGlmKCFzdGsuZW1wdHkoKSkKICAgICAgICByZXR1cm4gZmFsc2U7CiAgICByZXR1cm4gdHJ1ZTsKfQoKaW50IG1haW4oKSB7Cgljb3V0IDw8IGlzVmFsaWQoIigpe31bXSIpIDw8IGVuZGw7Cgljb3V0IDw8IGlzVmFsaWQoIigpeyh9W10iKSA8PCBlbmRsOwoJcmV0dXJuIDA7Cn0=