fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <string>
  4. #include <stack>
  5.  
  6. bool ArePair(char opening, char closing)
  7. {
  8. if(opening == '(' && closing == ')') return true;
  9. else if(opening == '{' && closing == '}') return true;
  10. else if(opening == '[' && closing == ']') return true;
  11. return false;
  12. }
  13.  
  14. bool AreParenthesesBalanced(std::string exp)
  15. {
  16. std::stack<char> s;
  17. for(int i = 0; i < exp.length(); i++)
  18. {
  19. if(s.empty())
  20. s.push(exp[i]);
  21. else
  22. {
  23. if(ArePair(s.top(), exp[i]))
  24. s.pop();
  25. else
  26. s.push(exp[i]);
  27. }
  28. }
  29. return s.empty() ? true : false;
  30. }
  31.  
  32. int main() {
  33. std::string exp;
  34. int ntests;
  35.  
  36.  
  37. std::cin >> ntests;
  38. while(ntests--){
  39. std::cin >> exp;
  40. std::cout << (AreParenthesesBalanced(exp) ? "YES" : "NO") << std::endl;
  41. }
  42. return 0;
  43. }
Success #stdin #stdout 0s 3420KB
stdin
3
)))))(((((
()()()
((()()))
stdout
NO
YES
YES