题解 | #括号序列#利用stack实现

括号序列

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

import java.util.*;


public class Solution {
    /**
     * 
     * @param s string字符串 
     * @return bool布尔型
     */
    public boolean isValid (String s) {
        // write code here
        //利用栈实现
        if("".equals(s)){
            return false;
        }
        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;
                } else {
                    char cur = stack.pop();
                    if((cur == '(' && next == ')') || (cur == '[' && next == ']')  || (cur == '{' && next == '}')){
                        continue;
                    } else {
                        return false;
                    }
                }
            }
        }
        if(stack.isEmpty()){
            return true;
        } else {
            return false;
        }
    }
}
全部评论

相关推荐

2025-12-30 16:42
同济大学 C++
仁狂躁使者:哎呀,不用担心,我当时配环境配了两天,项目捋不清就问问导师能不能用ai,慢慢就清了,会好起来的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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