mstoyanov7

Balanced Parenthesis

May 31st, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. #include <stack>
  2. #include <iostream>
  3.  
  4.  
  5. bool areBracketsBalanced(std::string input)
  6. {
  7. std::stack<char> stackWithBrackets;
  8. char x;
  9.  
  10. for (int i = 0; i < input.length(); i++)
  11. {
  12. if (input[i] == '(' || input[i] == '['
  13. || input[i] == '{')
  14. {
  15. stackWithBrackets.push(input[i]);
  16. continue;
  17. }
  18.  
  19. if (stackWithBrackets.empty())
  20. return false;
  21.  
  22. switch (input[i]) {
  23. case ')':
  24.  
  25. x = stackWithBrackets.top();
  26. stackWithBrackets.pop();
  27. if (x == '{' || x == '[')
  28. return false;
  29. break;
  30.  
  31. case '}':
  32.  
  33. x = stackWithBrackets.top();
  34. stackWithBrackets.pop();
  35. if (x == '(' || x == '[')
  36. return false;
  37. break;
  38.  
  39. case ']':
  40.  
  41. x = stackWithBrackets.top();
  42. stackWithBrackets.pop();
  43. if (x == '(' || x == '{')
  44. return false;
  45. break;
  46. }
  47. }
  48.  
  49. return (stackWithBrackets.empty());
  50. }
  51.  
  52. int main()
  53. {
  54. std::string input;
  55. std::cin >> input;
  56.  
  57. if (areBracketsBalanced(input))
  58. std::cout << "YES";
  59. else
  60. std::cout << "NO";
  61. return 0;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment