Valid Parentheses

Photo by Luca Bravo on Unsplash

Valid Parentheses

Hola! The question that I solved is a stack-based question called "Valid Parentheses" from LeetCode. It can be solved without stack but the time complexity, as well as space complexity, may increase.

Question The question states that we are given a string of parentheses ("()","{}","[]") and we have to find if the resultant string of parentheses is valid 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.

For example:

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

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

Approach In the stack-based approach we push every opening bracket("(", "{", "[") into the stack and if we encounter a closing bracket then we will check the top of the stack. If it contains the same opening bracket then we pop the stack or else we return false. An exception case would be if we encounter a closing bracket when the stack is empty because then we have nothing to pop out and in that case too we will return false. If in the end, the stack is empty then we will return true.

bool isValid(string s) {
        stack<char> st;
    for(int i=0;i<s.length();i++)
    {
        if(s[i]=='(' || s[i]=='{' || s[i]=='['){
            st.push(s[i]);
        }
        else if(st.empty() && (s[i]==']' || s[i]=='}' || s[i]==')')){
            return false;
        }
        else if(s[i]==')'){
            if(st.top()=='('){
                st.pop();
            }
            else{
                return false;

            }
        }
        else if(s[i]=='}'){
            if(st.top()=='{'){
                st.pop();
            }
            else{
                return false;
            }
        }
        else if(s[i]==']'){
            if(st.top()=='['){
                st.pop();
            }
            else{
                return false;
            }
        }
        else if(st.empty() && (s[i]==']' || s[i]=='}' || s[i]==')')){
            return false;
        }
    }

    if(!st.empty()){
        return false;
    }

        return true;

    }

Thank you for sticking this long. If you've any questions or better solutions then please drop them in the comment section. Byee.