题解 | 有效括号序列

有效括号序列

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

import java.util.*;
public class Solution {
    public boolean isValid (String s) {
        Deque<Character> stack = new ArrayDeque<>();
        stack.push('b');
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c=='['||c=='('||c=='{'){
                stack.push(c);
            }
            if(c==']'&&!stack.isEmpty()){
                if(stack.pop()!='[')return false;
                continue;
            }
            if(c==')'&&!stack.isEmpty()){
                if(stack.pop()!='(')return false;
                continue;
            }
            if(c=='}'&&!stack.isEmpty()){
                if(stack.pop()!='{')return false;
                continue;
            }
        }
        stack.pop();
        if(!stack.isEmpty())return false;
        else return true;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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