第三题输出括号匹配 输入包含 ”( ) L R D “
题目以后补充。。。。
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
String s = sc.nextLine();
char[] ch = s.toCharArray();
System.out.println(Arrays.toString(ch));
int[] ans = new int[n];
int p = -1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (ch[i] == '(' || (s.charAt(i) == ')')) {
p++;
sb.insert(p, ch[i]);
} else if (ch[i] == 'L' && p >= 0) {
if (p >= 0)
p--;
} else if (ch[i] == 'R' && p >= 0) {
if (p < sb.length() - 1)
p++;
} else if (ch[i] == 'D') {
if (p >= 0) {
sb.deleteCharAt(p);
p--;
}
}
ans[i] = test(sb);
System.out.println(sb);
}
System.out.println(Arrays.toString(ans));
}
static int test(StringBuilder sb) {
char[] ch = sb.toString().toCharArray();
Stack<Character> stack = new Stack<Character>();
int res = 0;
int maxTop = 0;
for (char c : ch) {
if (c == '(') {
stack.push(c);
maxTop = Math.max(maxTop, stack.size());
}
if (c == ')') {
res--;
if (!stack.isEmpty()) {
stack.pop();
res++;
}
}
}
if (stack.isEmpty()&&res==0) {
return maxTop;
}
while (!stack.isEmpty()) {
stack.pop();
res--;
}
return res;
}
}