20 Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

Solution1: stack

public boolean isValid(String s) {

        Stack<Character> st = new Stack<Character>();

        int numChar = s.length();
        for(int i = 0; i < numChar; i++) {
            if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') {
                st.push(s.charAt(i));
            }
            else {
                //1. when there is a right para need to be matched but stack is empty
                if(st.isEmpty()) return false;
                else {
                    //2. stack is not empty, but not match
                    if(s.charAt(i) == ')' && st.peek() != '(') return false;
                    else if(s.charAt(i) == ']' && st.peek() != '[') return false;
                    else if(s.charAt(i) == '}' && st.peek() != '{') return false;
                    //match
                    else st.pop(); 
                }
            }
        }

        //3. eventually, stack is not empty
        return st.empty();
    }

results matching ""

    No results matching ""