-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1190.java
63 lines (59 loc) · 2.12 KB
/
_1190.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.fishercoder.solutions.secondthousand;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class _1190 {
public static class Solution1 {
public String reverseParentheses(String s) {
Stack<Character> stack = new Stack<>();
Queue<Character> queue = new LinkedList<>();
for (char c : s.toCharArray()) {
if (c != ')') {
stack.push(c);
} else {
while (!stack.isEmpty() && stack.peek() != '(') {
queue.offer(stack.pop());
}
if (!stack.isEmpty()) {
stack.pop(); // pop off the open paren
}
while (!queue.isEmpty()) {
stack.push(queue.poll());
}
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.reverse().toString();
}
}
public static class Solution2 {
public static String reverseParentheses(String s) {
Deque<String> stack = new LinkedList<>();
for (char c : s.toCharArray()) {
if (c == '(' || Character.isAlphabetic(c)) {
stack.addLast(c + "");
} else {
StringBuilder innerSb = new StringBuilder();
while (!stack.isEmpty()) {
if (stack.peekLast().equals("(")) {
stack.pollLast();
break;
} else {
innerSb.append(stack.pollLast());
}
}
stack.addLast(innerSb.reverse().toString());
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pollLast());
}
return sb.reverse().toString();
}
}
}