有效的括号序列

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

样例

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

挑战

O(n)的时间,n为括号的个数

public class Solution {
    /**
     * @param s A string
     * @return whether the string is a valid parentheses
     */
    public boolean isValidParentheses(String s) {
        // Write your code here
        Stack<Integer> stk = new Stack<Integer>();
        for(int i = 0;i < s.length();++i){
            int pos = "(){}[]".indexOf(s.substring(i,i+1));
            if(pos%2 == 1){
                if(stk.isEmpty()||stk.pop()!= pos-1)
                   return false;
            }else {
                stk.push(pos);
            }
        }
        return stk.isEmpty();
    }
}
原文地址:https://www.cnblogs.com/wangnanabuaa/p/5122959.html