Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在leetcode题解/栈与队列一文中 对于4.用栈实现括号匹配的相关错误: #1214

Open
xjx403 opened this issue Oct 16, 2022 · 0 comments

Comments

@xjx403
Copy link

xjx403 commented Oct 16, 2022

  1. 用栈实现括号匹配
    给出的代码有问题,原代码在示例 ”(("中会返回true(实际应该返回false), 原因是会连续压栈两次。
    给出修改:
    在返回true之前加一个判断,如果当前堆栈不为空,则返回false,完整代码如下:
    public boolean isValid(String s) {
    //修改,减少运算量。
    if(s.length()%2 != 0){
    return false;
    }
    Stack stack=new Stack<>();
    for (char c:s.toCharArray()) {
    if(c == '(' || c== '{' || c == '['){
    stack.push(c);
    }else{
    if(stack.empty()) return false;
    char cStack=stack.pop();
    boolean b1= cStack=='(' && c!=')';
    boolean b2= cStack== '{' && c!='}';
    boolean b3= cStack== '[' && c!=']';
    if(b1 || b2 ||b3){
    return false;
    }
    }
    }
    //修改,避免“((”的情况。
    if(!stack.empty()){
    return false;
    }
    return true;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant