題目鏈接 傳送門
思路
代碼:
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;
}
}