Created
July 31, 2017 08:05
-
-
Save 0001vrn/24047dc10f0e6015a949fa63a051fcd5 to your computer and use it in GitHub Desktop.
Check for balanced parentheses in an expression
This file contains hidden or 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
| /* | |
| Given an expression string exp , write a program to examine whether | |
| the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp. | |
| For example, the program should print true for exp = “[()]{}{[()()]()}” | |
| and false for exp = “[(])” | |
| By : Varun Thakur | |
| Date : 31/07/2017 | |
| */ | |
| #include <stack> | |
| #include <iostream> | |
| using namespace std; | |
| bool isMatchingPair(char a, char b){ | |
| if(a == '[' && b == ']') | |
| return 1; | |
| if(a == '{' && b == '}') | |
| return 1; | |
| if(a == '(' && b == ')') | |
| return 1; | |
| return 0; | |
| } | |
| bool parenthesisChecker(string str) | |
| { | |
| stack<char> s; | |
| for(auto i:str) | |
| { | |
| if(i=='['||i=='{'||i=='(') | |
| s.push(i); | |
| if(i==']'||i=='}'||i==')') | |
| { | |
| if(s.empty()) | |
| return 0; | |
| else | |
| { | |
| char ch = s.top(); | |
| s.pop(); | |
| if(!isMatchingPair(ch,i)) | |
| return 0; | |
| } | |
| } | |
| } | |
| return s.empty(); | |
| } | |
| int main() { | |
| //code | |
| int t;cin>>t; | |
| while(t--){ | |
| string s;cin>>s; | |
| parenthesisChecker(s)?cout<<"balanced\n":cout<<"not balanced\n"; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment