题目
输出一串“())(()()(()”中正确匹配的括号串。
思路
通过借助Stack,对匹配的括号直接出栈,不匹配的括号要么直接不入栈,要么就剩在栈中,最后记录下这些未入栈的下标。
代码
public static void func(String str) {
if (str == null) {
System.out.println("Bad string");
return;
}
Stack<Integer> stack = new Stack<>();
List<Integer> list = new ArrayList<>();
for(int i=0; i<str.length(); i++) {
if (str.charAt(i) == '(') {
//做括号直接入栈
stack.push(i);
continue;
}
if (str.charAt(i) == ')') {
if (stack.isEmpty()) {
//右括号,但栈里没有左括号,即无效匹配
list.add(i);
} else {
//有效匹配
stack.pop();
}
}
}
while (!stack.isEmpty()) {
//无效匹配
list.add(stack.pop());
}
for (int i=0; i<str.length(); i++) {
if (!list.contains(i)) {
System.out.print(str.charAt(i));
}
}
}