括号最大嵌套深度

public class Main {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String str = in.nextLine();
            String newStr = str.replace('{', '(');
            newStr = newStr.replace('[', '(');
            newStr = newStr.replace('}', ')');
            newStr = newStr.replace(']', ')');
            Stack<Character> stack = new Stack<>();
            int max = 0;
            int cur = 0;
            for(char c:newStr.toCharArray()){
                if(c == '('){
                    stack.push(c);
                    cur++;
                    max = Math.max(max, cur);
                } else {
                    stack.pop();
                    cur--;
                }
            }
            System.out.println(max);
        }
    }

}
全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务