File tree 2 files changed +54
-15
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder
2 files changed +54
-15
lines changed Original file line number Diff line number Diff line change 10
10
* The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/
11
11
public class _20 {
12
12
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 ));
21
19
} 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 ()) {
27
21
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 ();
28
31
}
29
- stack .pop ();
30
32
}
31
33
}
34
+ return stack .isEmpty ();
32
35
}
33
- return stack .isEmpty ();
34
36
}
35
37
}
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments