Valid Parentheses

class Solution {
    public boolean isValid(String s) {
        Stack stack = new Stack<>();
        
        for (char c : s.toCharArray()){
            if(c=='(' || c=='['|| c =='{'){
                stack.push(c);
            }
            if(c==')'){
                if(stack.isEmpty() || stack.pop() != '('){
                    return false;
                }
            }
            if(c=='}'){
                if(stack.isEmpty() || stack.pop() != '{'){
                    return false;
                }
            }
            if(c==']'){
                if(stack.isEmpty() || stack.pop() != '['){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}

你可能感兴趣的:(Valid Parentheses)