Skip to content

Commit 6fdb918

Browse files
add test for 20
1 parent 1c72f84 commit 6fdb918

File tree

2 files changed

+54
-15
lines changed

2 files changed

+54
-15
lines changed

src/main/java/com/fishercoder/solutions/_20.java

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,28 @@
1010
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/
1111
public class _20 {
1212

13-
public boolean isValid(String s) {
14-
Deque<Character> stack = new ArrayDeque<>();
15-
for (int i = 0; i < s.length(); i++) {
16-
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
17-
stack.push(s.charAt(i));
18-
} else {
19-
if (stack.isEmpty()) {
20-
return false;
13+
public static class Solution1 {
14+
public boolean isValid(String s) {
15+
Deque<Character> stack = new ArrayDeque<>();
16+
for (int i = 0; i < s.length(); i++) {
17+
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {
18+
stack.push(s.charAt(i));
2119
} else {
22-
if (stack.peek() == '(' && s.charAt(i) != ')') {
23-
return false;
24-
} else if (stack.peek() == '{' && s.charAt(i) != '}') {
25-
return false;
26-
} else if (stack.peek() == '[' && s.charAt(i) != ']') {
20+
if (stack.isEmpty()) {
2721
return false;
22+
} else {
23+
if (stack.peek() == '(' && s.charAt(i) != ')') {
24+
return false;
25+
} else if (stack.peek() == '{' && s.charAt(i) != '}') {
26+
return false;
27+
} else if (stack.peek() == '[' && s.charAt(i) != ']') {
28+
return false;
29+
}
30+
stack.pop();
2831
}
29-
stack.pop();
3032
}
3133
}
34+
return stack.isEmpty();
3235
}
33-
return stack.isEmpty();
3436
}
3537
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.fishercoder;
2+
3+
import com.fishercoder.solutions._20;
4+
import org.junit.BeforeClass;
5+
import org.junit.Test;
6+
7+
import static org.junit.Assert.assertEquals;
8+
9+
public class _20Test {
10+
private static _20.Solution1 solution1;
11+
12+
@BeforeClass
13+
public static void setup() {
14+
solution1 = new _20.Solution1();
15+
}
16+
17+
@Test
18+
public void test1() {
19+
assertEquals(false, solution1.isValid("(]"));
20+
}
21+
22+
@Test
23+
public void test2() {
24+
assertEquals(false, solution1.isValid("([)]"));
25+
}
26+
27+
@Test
28+
public void test3() {
29+
assertEquals(true, solution1.isValid("()[]{}"));
30+
}
31+
32+
@Test
33+
public void test4() {
34+
assertEquals(true, solution1.isValid("()"));
35+
}
36+
37+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy