题解中有个更好的思路,stack存入的不是(的坐标,存入每次到左括号的字符串,拿到右括号就对其进行反转,更妙一些。
import java.util.Stack;
class Solution {public String reverseParentheses(String s) {Stack<Integer> stack = new Stack<>();char [] cs = s.toCharArray();StringBuilder sb = new StringBuilder();for(int i = 0; i < cs.length; i++){if(cs[i] == '('){stack.push(i);}if(cs[i] == ')'){//反转reverse(stack.pop(),i,cs);}}for(char c : cs){if(c == '(' || c == ')'){continue;}sb.append(c+"");}return sb.toString();}public void reverse(int left, int right, char [] cs){while(left <= right){char temp = cs[left];cs[left] = cs[right];cs[right] = temp;left++;right--;}}
}