Java Solution


  • 0
    A
    class Solution {
        public boolean isValid(String s) {
            if (s == null || s.equals("")) {
                return true;
            }
            Stack<Character> stack = new Stack<>();
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (c == '(') {
                    stack.push(')');
                } else if (c == '{') {
                    stack.push('}');
                } else if (c == '[') {
                    stack.push(']');
                } else if (c == ')' || c == '}' || c == ']') {
                    if (stack.isEmpty() || !stack.pop().equals(c)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return stack.isEmpty();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.