My Java Solution Sharing


  • 0
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i=0; i<s.length(); i++) {
            if(s.charAt(i) == '(') {
                stack.push('(');
            } else if(s.charAt(i) == '[') {
                stack.push('[');
            } else if(s.charAt(i) == '{') {
                stack.push('{');
            } else if(s.charAt(i) == ')') {
                if(stack.empty() || stack.pop() != '(') return false;
            } else if(s.charAt(i) == ']') {
                if(stack.empty() || stack.pop() != '[') return false;
            } else {
                if(stack.empty() || stack.pop() != '{') return false;
            }
        }
        return stack.empty();
    }

Log in to reply
 

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