Advertisement
Guest User

Untitled

a guest
Apr 21st, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. string isBalanced(string expr) {
  6.         stack<int> s;
  7.    
  8.         vector<int> cptOpen(3,0);
  9.         vector<int> cptClosed(3,0);
  10.        
  11.         for(int i=0; i < expr.length() ; i++){
  12.             if(expr[i]=='('){
  13.                 cptOpen[0]++;
  14.             }
  15.             if(expr[i]==')'){
  16.                 cptClosed[0]++;
  17.             }
  18.            
  19.             if(expr[i]=='['){
  20.                 cptOpen[1]++;
  21.             }
  22.             if(expr[i]==']'){
  23.                 cptClosed[1]++;
  24.             }
  25.            
  26.             if(expr[i]=='{'){
  27.                 cptOpen[2]++;
  28.             }
  29.             if(expr[i]=='}'){
  30.                 cptClosed[2]++;
  31.             }
  32.         }
  33.        
  34.         for(int i=0;i<3;i++){
  35.             if(cptOpen[i]!=cptClosed[i]){
  36.                 return "NO";
  37.             }
  38.         }
  39.        
  40.         for(int i=0;i<expr.length();i++){
  41.             if(expr[i]=='('){
  42.                 s.push(1);
  43.             }
  44.             if(expr[i]==')'){
  45.                 if(s.empty() || s.top()!=1){
  46.                     return "NO";
  47.                 }
  48.                 s.pop();
  49.             }
  50.            
  51.             if(expr[i]=='['){
  52.                 s.push(2);
  53.             }
  54.            
  55.             if(expr[i]==']'){
  56.                 if(s.empty() || s.top()!=2){
  57.                     return "NO";
  58.             }
  59.                 s.pop();
  60.             }
  61.            
  62.             if(expr[i]=='{'){
  63.                 s.push(3);
  64.             }
  65.             if(expr[i]=='}'){
  66.                 if(s.empty() || s.top()!=3){
  67.                     return "NO";
  68.                 }
  69.                 s.pop();
  70.             }
  71.         }
  72.         return "YES";
  73.     }
  74.  
  75. int main() {
  76.     int t;
  77.     cin >> t;
  78.     for(int a0 = 0; a0 < t; a0++){
  79.         string s;
  80.         cin >> s;
  81.         string result = isBalanced(s);
  82.         cout << result << endl;
  83.     }
  84.     return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement