[leetcode] 20. 有效的括号

20. 有效的括号

括号匹配,用栈即可。高中时第一次学栈后做的第一个题。。

class Solution {
    public boolean isValid(String s) {
        Stack<Character> characterStack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case '(':
                case '[':
                case '{':
                    characterStack.push(s.charAt(i));
                    break;
                case ')':
                    if (!characterStack.isEmpty() && characterStack.peek() == '(') {
                        characterStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case ']':
                    if (!characterStack.isEmpty() && characterStack.peek() == '[') {
                        characterStack.pop();
                        break;
                    } else {
                        return false;
                    }
                case '}':
                    if (!characterStack.isEmpty() && characterStack.peek() == '{') {
                        characterStack.pop();
                        break;
                    } else {
                        return false;
                    }
            }
        }

        return characterStack.isEmpty();
    }
}
posted @ 2018-07-01 18:13  ACBingo  阅读(117)  评论(0编辑  收藏  举报