Skip to content

Latest commit

 

History

History
25 lines (23 loc) · 726 Bytes

File metadata and controls

25 lines (23 loc) · 726 Bytes
class Solution {
    public boolean isValid(String s) {
        Stack <Character> stack = new Stack <Character>(); // create empty stack
        
        // traverse through each character
        for (char c: s.toCharArray()) {
            if (c == '(') {
                stack.push(')');
            } else if (c == '{') {
                stack.push('}');
            } else if (c == '[') {
                stack.push(']');
            // if opening brace does not match closing brace
            // or if there is no closing brace
            } else if (stack.isEmpty() || stack.pop() != c) {
                return false;

            }
        }
        // return null
        return stack.isEmpty();
    }
}