LeetCode 每日一题:1190. 反转每对括号间的子串
分析:
将括号的反转理解为逆序的遍历括号,然后通过栈预处理出每个括号对应的括号的索引方便跳转。
代码:
class Solution {
public String reverseParentheses(String s) {
Stack<Integer> st = new Stack<Integer>();
int[] book = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
st.push(i);
} else if (s.charAt(i) == ')') {
book[i] = st.peek();
book[st.pop()] = i;
}
}
StringBuilder re = new StringBuilder();
int index = 0, step = 1;
while (index < s.length()) {
if (s.charAt(index) == '(' || s.charAt(index) == ')') {
index = book[index];
step = -step;
} else {
re.append(s.charAt(index));
}
index += step;
}
return String.valueOf(re);
}
}