Header Ads Widget

Program to check that string containing valid parentheses or not

Program to check that string containing valid parentheses or not:- 

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', write a Program to check that string containing valid parentheses or not .

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.
Sample input:-
()[]{}
Sample output:-
Valid

Program to check that string containing valid parentheses or not:-

The objective of code is to check that the given string containing the valid parentheses or not. 




Code:-

#include<bits/stdc++.h>
using namespace std;

bool isValid(string s) {
char stack[5000];
int top=-1;
for(int i=0;i<s.size();i++)
{
if(s[i]=='(' || s[i]=='{' || s[i]=='[')
stack[++top]=s[i];
else
{
if(top<0)
return false;
if(s[i]==')')
{
if(stack[top]!='(')
return false;
top--;
}
if(s[i]=='}')
{
if(stack[top]!='{')
return false;
top--;
}
if(s[i]==']')
{
if(stack[top]!='[')
return false;
top--;
}
}
}
if(top==-1)
return true;
return false;
}
int main()
{
string str;
cout<<"Enter a string"<<endl;
cin>>str;
if(isValid(str)==true)
cout<<"Valid"<<endl;
else
cout<<"Not valid"<<endl;
}

Output:-
Enter a string
[{()}][]
Valid


Wipro :-

Infytq :-

Key Points;-

Hackerrank:-


C-tutorial:-

See more:-