Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

20. Valid Parentheses 🌟

Given a string s containing just the characters β€˜(β€˜, β€˜)’, β€˜{β€˜, β€˜}’, β€˜[’ and β€˜]’, determine if the input string is valid.

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.

O(N) Time and O(N) Space, straightforward solution

Code

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

Some slight simplification

Code

class Solution{
public:
    bool isValid(string s){
        stack<char> st;
        int n = s.size();
        if ((n & 1)) return false;
        for (int i = 0; i < n; i++){
            if (s[i] == '(' || s[i] == '[' || s[i] == '{'){
                st.push(s[i]);
            }
            else{
                if (st.empty() || (s[i] == ')' && st.top() != '(') || (s[i] == ']' && st.top() != '[') || (s[i] == '}' && st.top() != '{'))
                    return false;
                st.pop();
            }
        }
        return st.empty();
    }
};

Code-2

class Solution {
public:
    bool isValid(string s) {
        stack<char> st;
        for(auto x: s){
            if(x == '('||x == '['||x == '{')
                st.push(x);
            else{
                if(st.empty())
                    return false;
                char c = st.top();
                st.pop();
                if(c == '(' && x != ')')
                    return false;
                if(c == '[' && x != ']')
                    return false;
                if(c == '{' && x != '}')
                    return false;
            }
        }
        return st.empty();
    }
};