File tree Expand file tree Collapse file tree 2 files changed +54
-15
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +54
-15
lines changed Original file line number Diff line number Diff line change 1010 * The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.*/
1111public 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}
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