Created
October 29, 2013 00:49
-
-
Save mycodeschool/7207410 to your computer and use it in GitHub Desktop.
C++ Program to check for balanced parentheses in an expression using stack.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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"; | |
} |
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
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.