以栈的思维思考,在输入合法的情况下,每次‘(’入栈,就代表深度加一,每次‘)’入栈,就会与‘(’消除(即一个‘(’的出栈),而消除发生时,深度就会减一。
回到代码中,因为输入只有'('与')'与空的情况,而‘)’只会与‘(’进行消除,所以我们只需要一个变量记录当前深度即可
class Test{

    public static int getDeepth(String str){
        //deepth最大深度,count当前深度
        int deepth = 0,count = 0;
        if(str.length() > 0){
            for(int i=0;i < str.length();i++){
                //当前深度大于0 且 消除时
                if(count > 0 && str.charAt(i) == ')'){
                    //取当前深度与最大深度最大值
                    deepth = Math.max(deepth, count);
                    //消除操作后深度减一
                    count--;
                }else {
                    //深度加一
                    count++;
                }
            }
        }
        return deepth;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String i = in.next();
            System.out.println(getDeepth(i));
        }
    }

}