[LeetCode] Valid Parentheses

Problem

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.code

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.get

Note

創建堆棧stack。循環每一個元素放入堆棧或比較是否和棧頂元素成對。
循環結束後,若未拋出false,且堆棧爲空,說明全部parenthese都已一一對應。input

Solution

HashMap+Switch/case

public class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> map = new HashMap<>();
        map.put('(', ')');
        map.put('[', ']');
        map.put('{', '}');
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            Character ch = s.charAt(i);
            switch (ch) {
                case '{': case '[': case '(':
                    stack.push(ch);
                    break;
                case ')': case '}': case ']':
                    if (stack.isEmpty() || ch != map.get(stack.pop())) return false;
            }
        }
        return stack.isEmpty();
    }
}

if-else branches

public class Solution {
    /**
     * @param s: A string
     * @return: whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        char[] str = s.toCharArray();
        if (str.length % 2 != 0) return false;
        Stack<Character> stack = new Stack<>();
        for (char ch: str) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) {
                    return false;
                } else {
                    char top = stack.pop();
                    if ((ch == ')' && top != '(') || (ch == ']' && top != '[') || (ch == '}' && top != '{')) {
                        return false;
                    }
                }
            }
        }
        return stack.isEmpty();
    }
}
相關文章
相關標籤/搜索