[LeetCode] Valid Parentheses

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            char top = (stack.size() == 0)?  ' ' : stack.peek();
            if (c == ')') if (top != '(') return false; else stack.pop();
            else if (c == ']') if (top != '[') return false; else stack.pop();
            else if (c == '}') if (top != '{') return false; else stack.pop();
            else stack.add(c);
        }
        return stack.size() == 0;
    }
}

留言

  1. Titanium Profile - Titanium Art
    Our titanium titanium bikes for sale art prints offer a nipple piercing jewelry titanium complete palette of babyliss pro titanium characters titanium mig 170 and styles to create your own unique style. We're always looking for quality prints that have been created ford ecosport titanium

    回覆刪除

張貼留言