Skip to content

Commit 1f4751f

Browse files
add a solution for 1190
1 parent 1b8f6dc commit 1f4751f

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

src/main/java/com/fishercoder/solutions/secondthousand/_1190.java

+29
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.fishercoder.solutions.secondthousand;
22

3+
import java.util.Deque;
34
import java.util.LinkedList;
45
import java.util.Queue;
56
import java.util.Stack;
@@ -31,4 +32,32 @@ public String reverseParentheses(String s) {
3132
return sb.reverse().toString();
3233
}
3334
}
35+
36+
public static class Solution2 {
37+
38+
public static String reverseParentheses(String s) {
39+
Deque<String> stack = new LinkedList<>();
40+
for (char c : s.toCharArray()) {
41+
if (c == '(' || Character.isAlphabetic(c)) {
42+
stack.addLast(c + "");
43+
} else {
44+
StringBuilder innerSb = new StringBuilder();
45+
while (!stack.isEmpty()) {
46+
if (stack.peekLast().equals("(")) {
47+
stack.pollLast();
48+
break;
49+
} else {
50+
innerSb.append(stack.pollLast());
51+
}
52+
}
53+
stack.addLast(innerSb.reverse().toString());
54+
}
55+
}
56+
StringBuilder sb = new StringBuilder();
57+
while (!stack.isEmpty()) {
58+
sb.append(stack.pollLast());
59+
}
60+
return sb.reverse().toString();
61+
}
62+
}
3463
}

src/test/java/com/fishercoder/secondthousand/_1190Test.java

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,25 @@
11
package com.fishercoder.secondthousand;
22

33
import com.fishercoder.solutions.secondthousand._1190;
4-
import org.junit.BeforeClass;
5-
import org.junit.Test;
4+
import org.junit.jupiter.api.BeforeEach;
5+
import org.junit.jupiter.api.Test;
66

7-
import static org.junit.Assert.assertEquals;
7+
import static org.junit.jupiter.api.Assertions.assertEquals;
88

99
public class _1190Test {
1010
private static _1190.Solution1 solution1;
11+
private static _1190.Solution2 solution2;
1112

12-
@BeforeClass
13-
public static void setup() {
13+
@BeforeEach
14+
public void setup() {
1415
solution1 = new _1190.Solution1();
16+
solution2 = new _1190.Solution2();
1517
}
1618

1719
@Test
1820
public void test1() {
1921
assertEquals("dcba", solution1.reverseParentheses("(abcd)"));
22+
assertEquals("dcba", solution2.reverseParentheses("(abcd)"));
2023
}
2124

2225
@Test

0 commit comments

Comments
 (0)