Skip to content

Instantly share code, notes, and snippets.

@mycodeschool
Created October 29, 2013 00:49
Show Gist options
  • Save mycodeschool/7207410 to your computer and use it in GitHub Desktop.
Save mycodeschool/7207410 to your computer and use it in GitHub Desktop.
C++ Program to check for balanced parentheses in an expression using stack.
/*
C++ Program to check for balanced parentheses in an expression using stack.
Given an expression as string comprising of opening and closing characters
of parentheses - (), curly braces - {} and square brackets - [], we need to
check whether symbols are balanced or not.
*/
#include<iostream>
#include<stack>
#include<string>
using namespace std;
// Function to check whether two characters are opening
// and closing of same type.
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') return true;
else if(opening == '{' && closing == '}') return true;
else if(opening == '[' && closing == ']') return true;
return false;
}
bool AreParanthesesBalanced(string exp)
{
stack<char> S;
for(int i =0;i<exp.length();i++)
{
if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
S.push(exp[i]);
else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
{
if(S.empty() || !ArePair(S.top(),exp[i]))
return false;
else
S.pop();
}
}
return S.empty() ? true:false;
}
int main()
{
/*Code to test the function AreParanthesesBalanced*/
string expression;
cout<<"Enter an expression: "; // input expression from STDIN/Console
cin>>expression;
if(AreParanthesesBalanced(expression))
cout<<"Balanced\n";
else
cout<<"Not Balanced\n";
}
@diegoba90
Copy link

I'm having a hard time with this. How can i make it so that instead of having the user input the string of characters it instead reads it from a file that has lines of different expressions.

@rohitverma1999hack
Copy link

return S.empty() ? true:false; is kind of redundant (if true return true else return false).
It's not redundant
what if the input is "(".

@umamahesh33
Copy link

it will fail for the test case when we include the space in the user input because the taking of string input will not execute after a blank space

@shoaibrain
Copy link

shoaibrain commented Oct 9, 2020

`def balancedBrackets(string):
#remove all invalid characters. This is optional by the way.If your string only contains [{()}]. You don't have to change input string in any
way
string = [x for x in string if x in '[{()}]]']

stack = []

for char in string:
	if char in '([{':
		stack.append(char)
	else:
		if len(stack) == 0  or not arePair(stack[-1], char):
			return False
		else:
			stack.pop()
if len(stack) == 0:return True
return `False`

def arePair(opening,closing):
if opening == '(' and closing == ')':return True
elif opening == '[' and closing == ']': return True
elif opening == '{' and closing == '}':return True
return False
`

@BaseMax
Copy link

BaseMax commented Apr 11, 2021

@ibrahimBanat
Copy link

Solution Using JavaScript: you can also check the whiteboard and test from here:

class MultiBracketValidation {
  constructor() {
    this.stack = new Stack();
    this.opening = ["{", "(", "[", "<"];
    this.closing = ["}", ")", "]", ">"];
  }
  checkForValidation(input) {
    for (const char of input) {
      if (this.isOpening(char)) {
        this.stack.push(char);
      } else if (this.isClosing(char)) {
        if (
          this.stack.isEmpty() ||
          !this.isPair(this.stack.peek().value, char)
        ) {
          return false;
        } else {
          this.stack.pop();
        }
      }
    }
    return this.stack.isEmpty();
  }
  isOpening(char) {
    return this.opening.indexOf(char) >= 0;
  }
  isClosing(char) {
    return this.closing.indexOf(char) >= 0;
  }
  isPair(opening, closing) {
    return this.closing.indexOf(closing) === this.opening.indexOf(opening);
  }
}

@HarshKakran
Copy link

Hey, I am a beginner in programming, and tried to implement the pseudo code shared in the video using C++, can you guys share the reviews about the coding style.

bool checkBalancedParenthesis(string exp){
    stack<char> s;
    int n = exp.length();
    for(int i=0; i<n; i++){
        if (exp[i] == '{' || exp[i] == '(' || exp[i] == '['){
            s.push(exp[i]);
        }
        else if(exp[i] == '}' || exp[i] == ')' || exp[i] == ']'){
            if (s.empty())
            return false;
            switch (s.top())
            {
            case '(':
                if (exp[i] == ')')
                    {s.pop();
                    break;}
                else{
                    return false;
                }
            case '{':
                if (exp[i] == '}')
                    {s.pop();
                    break;}
                else{
                    return false;
                }
            case '[':
                if (exp[i] == ']')
                    {s.pop();
                    break;}
                else{
                    return false;
                }
            }
        }    
    }
    return s.empty()?true:false;
}

@AshAman999
Copy link

Hey, I am a beginner in programming, and tried to implement the pseudo code shared in the video using C++, can you guys share the reviews about the coding style.

bool checkBalancedParenthesis(string exp){
    stack<char> s;
    int n = exp.length();
    for(int i=0; i<n; i++){
        if (exp[i] == '{' || exp[i] == '(' || exp[i] == '['){
            s.push(exp[i]);
        }
        else if(exp[i] == '}' || exp[i] == ')' || exp[i] == ']'){
            if (s.empty())
            return false;
            switch (s.top())
            {
            case '(':
                if (exp[i] == ')')
                    {s.pop();
                    break;}
                else{
                    return false;
                }
            case '{':
                if (exp[i] == '}')
                    {s.pop();
                    break;}
                else{
                    return false;
                }
            case '[':
                if (exp[i] == ']')
                    {s.pop();
                    break;}
                else{
                    return false;
                }
            }
        }    
    }
    return s.empty()?true:false;
}

If you are waiting for the mentors to reply then they ain't goint to reply and apart from that yeah coding style looks good

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment