fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int isMatching(stack<char> &stk, char c){
  5. if(stk.empty()){
  6. return 0;
  7. }
  8. char topC = stk.top();
  9. if( (topC == '(' && c == ')') || (topC == '{' && c == '}') || (topC == '[' && c == ']') )
  10. return 1;
  11. return 0;
  12. }
  13.  
  14. bool isValid(string s) {
  15. stack<char> stk;
  16. int len = s.length();
  17. for(int i = 0; i < len; i++){
  18. if(s[i] == '(' || s[i] == '{' || s[i] == '['){
  19. stk.push(s[i]);
  20. continue;
  21. } else if((s[i] == ')' || s[i] == '}' || s[i] == ']') && isMatching(stk, s[i])){
  22. stk.pop();
  23. continue;
  24. }
  25. return false;
  26. }
  27. if(!stk.empty())
  28. return false;
  29. return true;
  30. }
  31.  
  32. int main() {
  33. cout << isValid("(){}[]") << endl;
  34. cout << isValid("(){(}[]") << endl;
  35. return 0;
  36. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1
0