leetcode 1111. 有效括號的嵌套深度——棧處理括號嵌套

題目鏈接 傳送門

思路

代碼:

class Solution {
    public int[] maxDepthAfterSplit(String seq) {
        int top=0;
        char[] c=seq.toCharArray();
        int[] ans=new int[c.length];
        for(int i=0;i<c.length;i++){
            if(c[i]=='('){
                top++;
                if((top&1)==0)ans[i]=1;
                else ans[i]=0;
            }
            else if(c[i]==')'){
                if((top&1)==0)ans[i]=1;
                else ans[i]=0;
                top--;
            }
        }
        return ans;
    }
    //拆分序列使得最大的深度最小,顯然應儘量平分序列深度,故將一半的深度
    //我們固然可以直接從深度的中間劈開,前一半歸給a,後一半歸給b,但這樣不好確定具體位置
    //我們還可以採取穿插的策略,奇數是a,偶數是b
    //括號序列最大深度問題,棧能達到的最大層數
    public int getDepth(char[] a){
        // char[] stack=new char[a.length];
        // int top=0,max=0;
        // for(int i=0;i<a.length;i++){
        //     if(a[i]=='('){
        //         stack[top++]=a[i];
        //         max=max>top?max:top;
        //     }
        //     else top--;
        // }
        // return max;
        //甚至完全不需要棧,只記錄‘(’出現的次數
        int top=0,max=0;
        for(int i=0;i<a.length;i++){
            if(a[i]=='('){
                top++;
                max=max>top?max:top;
            }
            else top--;
        }
        return max;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章