题解 | #有效括号序列#利用栈实现

有效括号序列

http://www.nowcoder.com/practice/37548e94a270412c8b9fb85643c8ccc2



public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    public boolean isValid (String s) {
        // write code here
        Stack<Character> stack = new Stack();
        for(int i = 0; i< s.length();i++){
            char next = s.charAt(i);
            if(next == '(' || next == '{' || next == '['){
                stack.push(next);
            } else {
                if(stack.isEmpty()){
                    return false;
                }
                char pop = stack.pop();
                if((pop == '(' && next != ')') || (pop == '{' && next != '}') || (pop == '[' && next != ']')){
                    return false;
                }
            }
        }
        if(stack.isEmpty()){
            return true;
        }
        return false;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务