fork download
  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4.  
  5. bool isBalanced(string s) {
  6. stack<char> st;
  7.  
  8. for (char ch : s) {
  9. if (ch == '(' || ch == '[' || ch == '{') {
  10. st.push(ch);
  11. } else {
  12. if (st.empty()) return false;
  13.  
  14. char top = st.top();
  15. if ((ch == ')' && top != '(') ||
  16. (ch == ']' && top != '[') ||
  17. (ch == '}' && top != '{')) {
  18. return false;
  19. }
  20. st.pop();
  21. }
  22. }
  23.  
  24. return st.empty();
  25. }
  26.  
  27. int main() {
  28. string s;
  29. while (cin >> s) {
  30. cout << (isBalanced(s) ? "YES" : "NO") << endl;
  31. }
  32. return 0;
  33. }
  34.  
Success #stdin #stdout 0.01s 5220KB
stdin
Standard input is empty
stdout
Standard output is empty