๐๐ Parenthesis Checker ๐๐
Statement ๐๐
Given an expression (containing Parenthesis) string
str
. you have to write a program to check whether the pair of brackets are in the correct order or not.
Example : 1 ๐๐
Input
str = "([{}])"
Output
YES
Explanatation
- ( [ { } ] ) ,
{
closed with}
,[
closed with]
and(
closed with)
.
Example : 2 ๐๐
Input
str = "({[}])"
Output
NO
Explanatation
- Parenthesis are not in order .
๐ป๐ป Before moving on to solution part , try this this question through following link : Problem link ๐๐
Logic ๐๐
- create an empty stack
s
. Traverse the string
str
- if you found any open brackets
push
character into the stack. else
- if( stack is empty ) : return
false
. - if top of stack element do not match with their corresponding closed bracket then return
false
. - if top of stack element matches with their corresponding closed bracket then pop that top element. and continue to next iteration.
- if( stack is empty ) : return
- if you found any open brackets
#include <bits/stdc++.h>
using namespace std;
bool check(char a, char b)
{
return ((a == '(' and b == ')') or
(a == '{' and b == '}') or
(a == '[' and b == ']'));
}
bool solve(string str)
{
stack<char> s;
for (int i = 0; i < str.length(); i++)
{
if (str[i] == '(' or str[i] == '[' or str[i] == '{')
{
s.push(str[i]);
}
else
{
if (s.empty() == true)
{
return false;
}
if (check(s.top(), str[i]))
{
s.pop();
}
else
{
return false;
}
}
}
return (s.empty() == true);
}
int main()
{
string s;
cin >> s;
if (solve(s))
cout << "YES" << endl;
else
cout << "NO" << endl;
return 0;
}
Complexity Analysis
Time | Space |
O(N) | O(N) |
ย