首页 > 其他 > 详细

有效的括号序列

时间:2016-01-12 01:14:48      阅读:231      评论:0      收藏:0      [点我收藏+]

给定一个字符串所表示的括号序列,包含以下字符: ‘(‘, ‘)‘,‘{‘‘}‘‘[‘ 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();
    }
}

 

有效的括号序列

原文:http://www.cnblogs.com/wangnanabuaa/p/5122959.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!