题目描述:
有效括号字符串 仅由 “(” 和 “)” 构成,并符合下述几个条件之一:
空字符串
连接,可以记作 AB(A 与 B 连接),其中 A 和 B 都是有效括号字符串
嵌套,可以记作 (A),其中 A 是有效括号字符串
类似地,我们可以定义任意有效括号字符串 s 的 嵌套深度 depth(S):
s 为空时,depth("") = 0
s 为 A 与 B 连接时,depth(A + B) = max(depth(A), depth(B)),其中 A 和 B 都是有效括号字符串
s 为嵌套情况,depth("(" + A + “)”) = 1 + depth(A),其中 A 是有效括号字符串
例如:"","()()",和 “()(()())” 都是有效括号字符串,嵌套深度分别为 0,1,2,而 “)(” 和 “(()” 都不是有效括号字符串。
给你一个有效括号字符串 seq,将其分成两个不相交的子序列 A 和 B,且 A 和 B 满足有效括号字符串的定义(注意:A.length + B.length = seq.length)。
现在,你需要从中选出 任意 一组有效括号字符串 A 和 B,使 max(depth(A), depth(B)) 的可能取值最小。
返回长度为 seq.length 答案数组 answer ,选择 A 还是 B 的编码规则是:如果 seq[i] 是 A 的一部分,那么 answer[i] = 0。否则,answer[i] = 1。即便有多个满足要求的答案存在,你也只需返回 一个。
示例 1:
输入:seq = “(()())”
输出:[0,1,1,1,1,0]
示例 2:
输入:seq = “()(())()”
输出:[0,0,0,1,1,0,1,1]
提示:
1 <= text.size <= 10000
重制版
这道题难度还是有的,首先计算seq的括号深度,这个是个难点,这里用了巧妙的方法,然后我们再次遍历seq发现当前的深度大于等于dep/2时就置为1代码
class Solution {
public int[] maxDepthAfterSplit(String seq) {
int[] result = new int[seq.length()];
int dep = getdep(seq);
dep /= 2;
char[] chars = seq.toCharArray();
int cur = 0;
int result1 = 0;
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
if (aChar == '(') {
if(cur >= dep){
result[i] = 1;
}
cur += 1;
result1 = Math.max(cur,result1);
} else {
if(cur > dep){
result[i] = 1;
}
cur --;
}
}
return result;
}
public int getdep(String seq) {
if (null == seq || 0 == seq.length()) {
return 0;
}
char[] chars = seq.toCharArray();
int cur = 0;
int result = 0;
for (int i = 0; i < chars.length; i++) {
char aChar = chars[i];
if (aChar == '(') {
cur += 1;
result = Math.max(cur,result);
} else {
cur --;
}
}
return result;
}
}
还有一种思路:
class Solution {
public int[] maxDepthAfterSplit(String seq) {
Stack<Integer> stack = new Stack();
int len = seq.length();
int[] res = new int[seq.length()];
int t = 0;
for(int i = 0; i < len; i++) {
char c = seq.charAt(i);
if (c == '(') {
stack.push(i);
res[i] = t;
t = (t + 1) % 2;
} else if (c == ')') {
int index = stack.pop();
res[i] = res[index];
t = (t + 1) % 2;
}
}
return res;
// 作者:keytian
// 链接:https://leetcode-cn.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/solution/yi-ge-stackjie-jue-wen-ti-by-keytian/
// 来源:力扣(LeetCode)
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
}
}
代码(错误的):一开始可以AC过了五个月再看同样的代码AC不了
leetcode的bug吧
class Solution {
public int[] maxDepthAfterSplit(String seq) {
int result[] = new int[seq.length()];
Stack<Character> stack = new Stack<>();
List<Integer> index = new ArrayList<>();
for (int i = 0; i < seq.length(); i++) {
char tem = seq.charAt(i);
if(stack.isEmpty()){
stack.push(tem);
index.add(i);
}else {
if(tem == ')'){
stack.pop();
if(stack.isEmpty())
index.add(i);
}else {
stack.push(tem);
}
}
}
for (Integer integer : index) {
result[integer] = 1;
}
return result;
}
}