[LeetCode] 1190. 反转每对括号间的子串
考察栈的使用,需要注意边界情况。不难,想全TestCase很容易1A通过
class Solution {
public String reverseParentheses(String s) {
Stack<Character> stack = new Stack<>();
if (s.length()==0) return "";
for (int i = 0;i<s.length();i++) {
if (s.charAt(i) == ')') {
reverse(stack);
} else {
stack.push(s.charAt(i));
}
}
String ans = "";
while (!stack.empty()) {
Character ch = stack.pop();
if (ch!='(') {
ans+=ch;
}
}
return new StringBuilder(ans).reverse().toString();
}
private void reverse(Stack<Character> stack) {
List<Character> tmp = new ArrayList<>();
while (true) {
Character ch = stack.pop();
if (ch == '(') {
int i=0;
while (i<tmp.size()) {
stack.push(tmp.get(i++));
}
break;
}
tmp.add(ch);
}
}
}