算法分享第5题

2017-12-22  本文已影响0人  DevWang
题目:Given a string containing just the characters '(',')','{','}','[' and ']', determine if the input string a valid.
the brackets must close in the correct order.
如:'()' and "()[]{}" are all valid but "(]" and "([)]" are not.




















思路:

匹配成功 - ()[]{} 匹配失败 - ([)]

代码:

private boolean match(String str) {
    int length = str.length();
    Stack stack = new Stack();
    for (int index = 0; index < length; index++) {
        char ch = str.charAt(index);
        switch (ch) {
            case '(':
            case '{':
            case '[':
                // 左括号进栈
                stack.push(ch);
                break;
            case ')':
                // 右括号 栈为空 返回false
                if (stack.empty()) {
                    return false;
                // 右括号 栈顶元素不是对应左括号返回false
                } else if ('(' != (char) stack.pop()) {
                    return false;
                }
                break;
            case '}':
                if (stack.empty()) {
                    return false;
                } else if ('{' != (char) stack.pop()) {
                    return false;
                }
                break;
            case ']':
                if (stack.empty()) {
                    return false;
                } else if ('[' != (char) stack.pop()) {
                    return false;
                }
                break;
            default:
                break;
        }
    }
    // 字符串遍历结束后栈为空则代表所有括号匹配成功
    return stack.empty();
}
上一篇 下一篇

猜你喜欢

热点阅读