1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public String reverseParentheses(String s) { StringBuffer sb = new StringBuffer(); Stack<Character> stack = new Stack<>(); int count = 0; boolean bool = true; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') { bool = true; count++; } else if (s.charAt(i) == ')') { bool = false; count--; }
if (count == 0 && s.charAt(i) != ')') { sb.append(s.charAt(i)); }else { if (bool) { stack.add(s.charAt(i)); }else { String str = ""; while (!stack.isEmpty() && stack.peek() != '(') { str = str + stack.pop(); } if (!stack.isEmpty()){ stack.pop(); }
if (stack.isEmpty()) { sb.append(str); }else { for (int j = 0; j < str.length(); j++) { stack.add(str.charAt(j)); } } } bool = true; } } return sb.toString(); } }
|