孙兴斌*_*孙兴斌 5 java string algorithm
我需要找出第一个最外层(不是嵌套)括号索引.
例如
[] output: 0, 1
1[2] output: 1, 3
3[a2[c]]2[abc]3[cd] output: 1, 7
Run Code Online (Sandbox Code Playgroud)
我可以通过很多条件找到它,当前代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
有更多的clean方法吗?
使用a Stack可能更优雅:
String input = "3[a2[c]]2[abc]3[cd]ef";
Stack<Integer> stack = new Stack<> ();
int first = -1;
int second = -1;
for (int index = 0; index < input.length(); index++) {
if (input.charAt(index) == '[') {
stack.push(index);
} else if (input.charAt(index) == ']' && !stack.isEmpty ()) {
first = stack.pop ();
if (stack.isEmpty ()) {
second = index;
break;
}
}
}
if (first >= 0 && second >= 0) {
System.out.println(first);
System.out.println(second);
} else {
System.out.println ("not found");
}
Run Code Online (Sandbox Code Playgroud)