C++ program called that reads a string and check if it’s well-formed or not.
ex== The input has only one string with the characters {, }, (, ), [, and ]. If the different types of brackets match in the correct order, we say that it’s well-matched. For example, the sample input is well-matched. As another example, “[()[]{()()}]” is also well-matched. But “{]” and “{()[[]}” are not well-matched.
Input 0
[()[]{()(
Output 0
FALSE
Input 1
(((((((((([[[[[[[[[[{{{{{{{{{{[]()}}}}}}}}}}]]]]]]]]]]))))))))))
Output 1
TRUE
#include<bits/stdc++.h>
using namespace std;
bool Pbalanced(string input)
{
stack<char> som;
char x;
for (int i=0; i<input.length(); i++)
{
if (input[i]=='('||input[i]=='['||input[i]=='{')
{
som.push(input[i]);
continue;
}
if (som.empty())
return false;
switch (input[i])
{
case ')':
x = som.top();
som.pop();
if (x=='{' || x=='[')
return false;
break;
case '}':
x = som.top();
som.pop();
if (x=='(' || x=='[')
return false;
break;
case ']':
x = som.top();
som.pop();
if (x =='(' || x == '{')
return false;
break;
}
}
return (som.empty());
}
int main()
{
string input;
cout<<"Enter the input: ";
cin>>input;
cout<<Pbalanced(input);
return 0;
}
Get Answers For Free
Most questions answered within 1 hours.