jasonpogi1669

Upgraded Balanced Parentheses using C++

Feb 10th, 2021 (edited)
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.18 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <stack>
  5.  
  6. using namespace std;
  7.  
  8. int main() {
  9.     string x;
  10.     stack < char, vector<char> > iStack;
  11.     cout << "Enter series of parentheses: ";
  12.     getline(cin, x);
  13.     char ch;
  14.     int cnt = 0;
  15.     for (int i = 0; i < x.length(); i++) {
  16.         if (x[i] == '(' || x[i] == '{' || x[i] == '[') {
  17.             cnt++;
  18.             iStack.push(x[i]);
  19.         } else {
  20.             if (iStack.empty()) {
  21.                 break;
  22.             }
  23.             if (x[i] == ')') {
  24.                 if (iStack.top() == '(') {
  25.                     cnt++;
  26.                     iStack.pop();
  27.                 }
  28.             } else if (x[i] == '}') {
  29.                 if (iStack.top() == '{') {
  30.                     cnt++;
  31.                     iStack.pop();
  32.                 }
  33.             } else if (x[i] == ']') {
  34.                 if (iStack.top() == '[') {
  35.                     cnt++;
  36.                     iStack.pop();
  37.                 }
  38.             }
  39.         }  
  40.     }
  41.     if (iStack.empty() && cnt == (int) x.size()) {
  42.         cout << "Balance!" << endl;
  43.     } else {
  44.         cout << "Not Balance!" << endl;
  45.     }
  46.     return 0;
  47. }
Add Comment
Please, Sign In to add comment