File tree 3 files changed +99
-0
lines changed
3 files changed +99
-0
lines changed Original file line number Diff line number Diff line change
1
+ package org .sean .stack ;
2
+
3
+ import java .util .Stack ;
4
+
5
+ // 20. Valid Parentheses
6
+ public class ParenthesesValidator {
7
+ public boolean isValid (String s ) {
8
+ if (s == null ) {
9
+ return false ;
10
+ }
11
+
12
+ Stack <Character > stack = new Stack <>();
13
+ for (int i = 0 ; i < s .length (); i ++) {
14
+ char ch = s .charAt (i );
15
+ if (ch == '(' || ch == '{' || ch == '[' ) {
16
+ stack .push (ch );
17
+ }
18
+
19
+ if (ch == ')' || ch == '}' || ch == ']' ) {
20
+ if (stack .isEmpty ()) {
21
+ return false ;
22
+ } else {
23
+ Character outCh = stack .pop ();
24
+ switch (ch ) {
25
+ case ')' :
26
+ if (outCh != '(' )
27
+ return false ;
28
+ break ;
29
+ case '}' :
30
+ if (outCh != '{' )
31
+ return false ;
32
+ break ;
33
+ case ']' :
34
+ if (outCh != '[' )
35
+ return false ;
36
+ break ;
37
+ }
38
+ }
39
+ }
40
+ }
41
+
42
+ return stack .isEmpty ();
43
+ }
44
+ }
Original file line number Diff line number Diff line change
1
+ package org .sean .tree ;
2
+
3
+ /**
4
+ * Definition for a binary tree node.
5
+ * public class TreeNode {
6
+ * int val;
7
+ * TreeNode left;
8
+ * TreeNode right;
9
+ * TreeNode(int x) { val = x; }
10
+ * }
11
+ */
12
+ // 617. Merge Two Binary Trees
13
+ class TreeMerger {
14
+
15
+ public TreeNode mergeTrees (TreeNode t1 , TreeNode t2 ) {
16
+ if (t1 == null && t2 == null ) {
17
+ return null ;
18
+ }
19
+
20
+ if (t1 == null )
21
+ return t2 ;
22
+
23
+ if (t2 == null )
24
+ return t1 ;
25
+
26
+ t1 .val += t2 .val ;
27
+
28
+ t1 .left = mergeTrees (t1 .left , t2 .left );
29
+ t1 .right = mergeTrees (t1 .right , t2 .right );
30
+
31
+ return t1 ;
32
+ }
33
+ }
Original file line number Diff line number Diff line change
1
+ package org .sean .stack ;
2
+
3
+ import org .junit .Assert ;
4
+ import org .junit .Before ;
5
+ import org .junit .Test ;
6
+
7
+ public class ParenthesesValidatorTest {
8
+
9
+ private ParenthesesValidator validator ;
10
+
11
+ @ Before
12
+ public void setUp () throws Exception {
13
+ validator = new ParenthesesValidator ();
14
+ }
15
+
16
+ @ Test
17
+ public void isValid () {
18
+ Assert .assertTrue (validator .isValid ("" ));
19
+ Assert .assertFalse (validator .isValid ("([)]" ));
20
+ Assert .assertTrue (validator .isValid ("{[]}" ));
21
+ }
22
+ }
You can’t perform that action at this time.
0 commit comments