0% found this document useful (0 votes)
27 views2 pages

Balanced Paranthesis

This C++ code defines a function to check if parentheses, brackets and braces are balanced in an expression. It uses a stack to keep track of opening symbols and pops them when the corresponding closing symbol is encountered, returning true if the stack is empty after parsing the whole expression.

Uploaded by

Yashika Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views2 pages

Balanced Paranthesis

This C++ code defines a function to check if parentheses, brackets and braces are balanced in an expression. It uses a stack to keep track of opening symbols and pops them when the corresponding closing symbol is encountered, returning true if the stack is empty after parsing the whole expression.

Uploaded by

Yashika Aggarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

#include<stack>
using namespace std;

int length(char *exp){


int length=0;
for(int i=0;exp[i]!='\0';i++)
length++;
return length;
}

bool checkBalanced(char *exp){


stack<int> st;
int l =length(exp);
for(int i = 0 ; i < l ; i++){

if(exp[i]=='('||exp[i]=='{'||exp[i]=='['){
st.push(exp[i]);
continue;
}

else if(exp[i]==')'){
if(st.empty() == false){
if(st.top()=='(')
st.pop();
}
else
return false;
}

else if(exp[i]=='}'){
if(st.empty() == false){
if(st.top()=='{')
st.pop();
}
else
return false;
}
else if(exp[i]==']'){
if(st.empty() == false){
if(st.top()=='[')
st.pop();
}
else
return false;
}

if(st.empty()==true){
return true;
}
else
return false;
}
int main() {
char input[100000];
cin.getline(input, 100000);
if(checkBalanced(input)) {
cout << "true" << endl;
}
else {
cout << "false" << endl;
}
}

You might also like