Valid Parentheses

    0

    0

    Mansimar Anand

    Check if the parentheses are valid or not

    class Solution {
        public boolean isValid(String s) {
            if (s.length() == 1) return false;
            Stack<Character> st = new Stack<>();
            for (int i = 0 ; i < s.length() ; ++i) {
                char c = s.charAt(i);
                if (c == '(' || c == '[' || c == '{') {
                    st.push(c);
                }
                else {
                    if (st.empty()) return false;
                    else if (st.peek() == '(' && c == ')') st.pop();
                    else if (st.peek() == '{' && c == '}') st.pop();
                    else if (st.peek() == '[' && c == ']') st.pop();
                    else return false;
                }
            }
            return st.empty();
        }
    }
    
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.