LeetCode 1190. 反转每对括号间的子串
原题链接
简单
作者:
autumn_0
,
2025-01-17 23:26:33
,
所有人可见
,
阅读 2
import java.util.Stack;
class Solution {
public String reverseParentheses(String s) {
char[] cs = s.toCharArray();
Stack<Integer> stk = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stk.add(i);
} else if (s.charAt(i) == ')') {
int j = stk.pop();
reverse(cs, j, i);
}
}
StringBuilder sb = new StringBuilder();
for (char c : cs) {
if (c != '(' && c != ')') {
sb.append(c);
}
}
return sb.toString();
}
public void reverse(char[] cs, int l, int r) {
while (l < r) {
char c = cs[l];
cs[l] = cs[r];
cs[r] = c;
l++;
r--;
}
}
}
import java.util.Stack;
class Solution {
public String reverseParentheses(String s) {
int n = s.length();
int[] ps = new int[n];
Stack<Integer> stk = new Stack<>();
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '(') {
stk.add(i);
} else if (s.charAt(i) == ')') {
int j = stk.pop();
ps[i] = j;
ps[j] = i;
}
}
StringBuilder sb = new StringBuilder();
int d = 1;
for (int i = 0; i < n; i += d) {
if (s.charAt(i) == '(' || s.charAt(i) == ')') {
i = ps[i];
d = -d;
} else {
sb.append(s.charAt(i));
}
}
return sb.toString();
}
}