O MatchingBracesTestCases - Notepad File Edit Format View Help (a+b) (a+b*(c-d))
ID: 3738057 • Letter: O
Question
O MatchingBracesTestCases - Notepad File Edit Format View Help (a+b) (a+b*(c-d)) (e+f) (g-h) (a+b*[C-d])[e+f{g-h}] (a+b*[C-d])e+f{g-h}] > run MatchingBraces Enter String: (a+b) Matching () pairs: 1 Matching [] pairs: 0 Matching {} pairs: 0 > run MatchingBraces Enter String: (a+b*(c-d))e+f)(g-h) Matching (0 pairs: 4 Matching [] pairs: 0 Matching {} pairs: 0 > run Matching Braces Enter String: (a+b^[c-d])[erf{g-h}] Matching (1) pairs: 1 Matching [] pairs: 2 Matching {} pairs: 1 > run Matching Braces Enter String: (a+h*[e-d])e+f[g-h} Matching (0 pairs: 1 Unbalanced [] Matching (0 pairs: 1Explanation / Answer
Following is the c++ code:
#include<iostream>
#include<stack>
#include<string>
#include <fstream> // To use ifstream
#include <math.h>
#include<stdlib.h>
#include <vector>
using namespace std;
// Function to check whether two characters are opening
// and closing of same type.
int a1 = 0;
int a2 = 0;
int a3 = 0;
int a4 = 0;
bool ArePair(char opening,char closing)
{
if(opening == '(' && closing == ')') { a1+=1; return true;}
else if(opening == '{' && closing == '}') { a2+=1; return true;}
else if(opening == '[' && closing == ']') { a3+=1; return true;}
else if(opening == '<' && closing == '>') { a4+=1; 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] == '[' || exp[i] == '<')
S.push(exp[i]);
else if(exp[i] == ')' || 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()
{
string str;
cout<<" Enter String: ";
cin>>str;
{
if(AreParanthesesBalanced(str))
{
cout<<" Balanced ";
cout<<" Matching () pairs: "<<a1;
cout<<" Matching [] pairs: "<<a3;
cout<<" Matching {} pairs: "<<a2;
}
else{
cout<<"Not Balanced ";
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.