有效的括号序列

2017-09-25  本文已影响0人  zhujiaqqq

描述

给定一个字符串所表示的括号序列,包含以下字符: (, ), {, }, [], 判定是否是有效的括号序列。

样例

括号必须依照 () 顺序表示, ()[]{} 是有效的括号,但 ([)]则是无效的括号

实现

public class Solution {
    /*
     * @param s: A string
     * @return: whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // write your code here
         if (s.length() % 2 == 1) {
            return false;
        }

        if (s.length() == 0) {
            return true;
        }

        byte[] bytes = s.getBytes();
        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            if (i == 0) {
                list.add(bytes[i]);
            } else {
                switch (bytes[i]){
                    case '{':
                        list.add(0,bytes[i]);
                        break;
                    case '[':
                        list.add(0,bytes[i]);
                        break;
                    case '(':
                        list.add(0,bytes[i]);
                        break;
                    case '}':
                        if (list.isEmpty()) {
                            return false;
                        }
                        if (list.get(0) == '{') {
                            list.remove(0);
                            break;
                        } else {
                            return false;
                        }
                    case ']':
                        if (list.isEmpty()) {
                            return false;
                        }
                        if (list.get(0) == '[') {
                            list.remove(0);
                            break;
                        } else {
                            return false;
                        }
                    case ')':
                        if (list.isEmpty()) {
                            return false;
                        }
                        if (list.get(0) == '(') {
                            list.remove(0);
                            break;
                        } else {
                            return false;
                        }
                }
            }
        }
        if (list.size() != 0) {
            return false;
        }
        return true;
    }
}

请关注我的个人网站:https://zhujiaqqq.github.io/

上一篇 下一篇

猜你喜欢

热点阅读