balanced brackets

A bracket is considered to be any one of the following characters: (, ), {, }, [, or ].

Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {},and ().

A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets enclose a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ].

By this logic, we say a sequence of brackets is balanced if the following conditions are met:

It contains no unmatched brackets.
The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets.
Given n strings of brackets, determine whether each sequence of 
brackets is balanced. If a string is balanced, return YES. Otherwise, return NO.

Example:

Input:  s = "{[()]}"
Output: YES

Approach

C++

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

bool balancedBracket(string s)
{
    int n = s.size();
    stack<charst;
    int flag = 0;
    for (int i = 0i < ni++)
    {
        if (s[i] == '(' || s[i] == '{' || s[i] == '[')
            st.push(s[i]);
        else
        {
            if (st.empty())
            {
                flag = 1;
                break;
            }
            else
            {
                if (s[i] == ')' && st.top() != '(')
                {
                    flag = 1;
                    break;
                }
                else if (s[i] == '}' && st.top() != '{')
                {
                    flag = 1;
                    break;
                }
                else if (s[i] == '[' && st.top() != ']')
                {
                    flag = 1;
                    break;
                }
                else
                    st.pop();
            }
        }
    }
    if (flag == 1)
        return false;
    else
    {
        if (st.empty())
            return true;
        else
            return false;
    }
}
int main()
{

    string s = "{[()]}";

    if (balancedBracket(s))
        cout << "YES\n";
    else
        cout << "NO\n";

    return 0;
}


No comments:

Post a Comment