我需要找到第一个最外层(非嵌套)括号的索引。
例如:
我可以通过许多条件找到它,当前代码:
例如:
[] output: 0, 1
1[2] output: 1, 3
3[a2[c]]2[abc]3[cd] output: 1, 7
我可以通过许多条件找到它,当前代码:
public static void main(String[] args) {
String input = "3[a2[c]]2[abc]3[cd]ef";
int first = 0;
int second = 0;
int count = 0;
boolean found = false;
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index) == '[') {
count++;
if (found == false) {
found = true;
first = index;
}
} else if (input.charAt(index) == ']') {
count--;
if (found && count == 0) {
second = index;
break;
}
}
}
System.out.println(first);
System.out.println(second);
}
有更加简洁
的方法吗?