SHARE
TWEET

Untitled

a guest Jun 24th, 2019 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <stack>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. bool checkParentheses(string str, stack<char> s) {
  8.     int flag = 0;
  9.     char top;
  10.     for(int i=0;i<str.length();i++) {
  11.     if(str[i] == '(' || str[i] == '{' || str[i] == '[') {
  12.         s.push(str[i]);
  13.     }
  14.     else {
  15.         if(s.empty()) {
  16.         flag = 1;
  17.         break;
  18.         }
  19.         else {
  20.         top = s.top();
  21.         }
  22.         if(str[i] == ')' && top == '('){
  23.         s.pop();
  24.         }
  25.         else if(str[i] == '}' && top == '{'){
  26.         s.pop();
  27.         }
  28.         else if(str[i] == ']' && top == '['){
  29.         s.pop();
  30.         }
  31.         else {
  32.         flag = 1;
  33.         break;
  34.         }
  35.  
  36.     }
  37.  
  38.     }
  39.     if(s.empty() && flag == 0) {
  40.     return true;
  41.     }
  42.     else if (flag == 1) {
  43.     return false;
  44.     }
  45.     else {
  46.     return false;
  47.     }
  48.  
  49.  
  50. }
  51.  
  52.  
  53.  
  54. int main() {
  55.     stack <char> s;
  56.     string str;
  57.     cout << "Enter an expression with brackets: " << endl;
  58.     cin >> str;
  59.     cout << str << endl;
  60.     if(checkParentheses(str, s)) {
  61.     cout << "Expression is valid!" << endl;
  62.     }
  63.     else {
  64.     cout << "Expression is not valid" << endl;
  65.     }
  66. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top