leetcode:那些年我遇到过的编程题017:有效括号的嵌套深度
我首先想到的是动态规划,能不能把括号拆分一下,分别划分A,B两个序列。设定一个栈,没找到一对()就把她们划分到A,或者B中。
public int[] maxDepthAfterSplit(String seq) {
if (seq == null || seq.equals("")) return new int[0];
Stack<Character> stack = new Stack<>();
int[] res = new int[seq.length()];
//遍历
for (int i = 0; i < seq.length(); i++) {
char c = seq.charAt(i);
if (c == '(') {//入栈,记录括号对所在深度,奇数用0标记,偶数用1标记。
res[i] = stack.size() % 2;
stack.push(c);
} else {//出栈,记录括号对所在深度,奇数用0标记,偶数用1标记。
stack.pop();
res[i] = stack.size() % 2;
}
}
return res;
}
作者:jerrymouse1998
链接:https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/solution/javazhan-shi-xian-zuo-ti-wu-fen-zhong-du-ti-liang-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
可以看到由于由于不断访问栈会大大延长内存运算时间
但是其实我们不一定非要使用一个栈
public class Solution {
public int[] maxDepthAfterSplit(String seq) {
int[] ans = new int [seq.length()];
int idx = 0;
for(char c: seq.toCharArray()) {
ans[idx++] = c == '(' ? idx & 1 : ((idx + 1) & 1);
}
return ans;
}
}