题目摸这

很明显这题要使用堆栈的数据结构,当遇到([{时压栈,遇到}])时出栈并判断是否匹配
最后在返回的时候注意判断下堆栈是否为空

class Solution {
    public boolean isValid(String s) {
        if (s.equals("")) return true;
        if (s.length() % 2 == 1) return false;
        Stack<Character> stack = new Stack<>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            Character c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                stack.push(c);
            } else {
                if (stack.empty()) return false;
                Character ch = stack.pop();
                if ((ch == '{' && c != '}') || (ch == '[' && c != ']') || (ch == '(' && c != ')')) {
                    return false;
                }
            }
        }
        return stack.empty();
    }
}

标签: leetcode, java

添加新评论