Question: I have to write a testing program for parenthesis. For example, the brackets must close in the correct order, () and ()[]{} are all valid

I have to write a testing program for parenthesis. For example, the brackets must close in the correct order, "()" and "()[]{}" are all valid but "([])" is not.

Here is my program.

bool isValid(string s)

{

stack parenthesis;

for (int i = 0; i < s.size(); i++)

{

if(s[i] == '(' || s[i] == '[' || s[i] == '{' )

parenthesis.push(s[i]);

else

{

if(parenthesis.empty())

return false;

if(s[i] == ')' && parenthesis.top() != '(')

return false;

if(s[i] == ']' && parenthesis.top() != '[')

return false;

if(s[i] == '}' && parenthesis.top() != '{')

return false;

parenthesis.pop();

}

}

return parenthesis.empty();

}

Here is the main program:

int main()

{

string s;

cout << "Input string" << endl;

cin >> s;

if(isValid(s))

cout << "Valid" << endl;

else

cout << "Invalid" << endl;

return 0;

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!