Joey LIU | NANTSOU


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            if (stack.size() > 0 && s.charAt(i) == '}' && stack.peek().equals('{')) {
                stack.pop();
            } else if (stack.size() > 0 && s.charAt(i) == ']' && stack.peek().equals('[')) {
                stack.pop();
            } else if (stack.size() > 0 && s.charAt(i) == ')' && stack.peek().equals('(')) {
                stack.pop();
            } else {
                stack.push(s.charAt(i));
            }
        }
        return stack.size() == 0;
    }
}