Leetcode 1190
5.26的每日一题,需从内到外
翻转字符串 ,我们可以遇到)
就开始翻转内容
可以用stack
来存储每个(
的index,找到第一个)
的时候即为优先级最高的里面,开始第一次翻转char[]数组
Sample input:"(abcd)" output:"dcba"
public String reverseParentheses(String s) {
StringBuilder sb = new StringBuilder();//用stringbuilder构建字符串
char[] chs = s.toCharArray();
int n = s.length();
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < n; i++) {
if (chs[i] == '(') {//记录index
stack.push(i);
}
if (chs[i] == ')') {//匹配,开始
reverse(chs, stack.pop() + 1, i);
}
}
for (int i = 0; i < n; i++) {
if (chs[i] != '(' && chs[i] != ')') {
sb.append(chs[i]);
}
}
return sb.toString();
}
private void reverse(char[] chs, int low, int high) {
while (low < high) {//左右双指针往中间交换char
char temp = chs[low];
chs[low++] = chs[high];
chs[high--] = temp;
}
}