Parenthesis Checker

ยท

2 min read

Parenthesis Checker

๐Ÿ”Ž๐Ÿ”Ž 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.
#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

TimeSpace
O(N)O(N)
ย