Advertisement
Niloy007

BalanceProblemUsingStack

Mar 19th, 2020
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. bool balanceCheck(string str) {
  5.     stack<char> stack;
  6.     char x;
  7.  
  8.     for(int i = 0; i < str.length(); i++) {
  9.         if(str[i] == '(' || str[i] == '{' || str[i] == '[') {
  10.             stack.push(str[i]);
  11.             continue;
  12.         }
  13.         if(stack.empty()) {
  14.             return false;
  15.         }
  16.  
  17.         if(str[i] == ')') {
  18.             x = stack.top();
  19.             stack.pop();
  20.             if(x == '{' || x == '[')
  21.                 return false;
  22.         } else if(str[i] == '}') {
  23.             x = stack.top();
  24.             stack.pop();
  25.             if(x == '(' || x == '[') {
  26.                 return false;
  27.             }
  28.         } else if(str[i] == ']') {
  29.             x = stack.top();
  30.             stack.pop();
  31.             if(x == '(' || x == '{') {
  32.                 return false;
  33.             }
  34.         }
  35.     }
  36.     return stack.empty();
  37. }
  38.  
  39.  
  40. int main() {
  41.     string st;
  42.     int n;
  43.     cin >> n;
  44.  
  45.     while(n--) {
  46.         cin >> st;
  47.         if (balanceCheck(st)) {
  48.             cout << "YES" << endl;
  49.         } else {
  50.             cout << "NO" << endl;
  51.         }
  52.     }
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement