File tree Expand file tree Collapse file tree 1 file changed +68
-0
lines changed
InterviewPrograms/src/com/hackerrank Expand file tree Collapse file tree 1 file changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .hackerrank ;
2
+
3
+ import java .util .ArrayList ;
4
+ import java .util .Scanner ;
5
+
6
+ public class BalancedBrackets {
7
+ public static void main (String [] args ) {
8
+ Scanner scanner = new Scanner (System .in );
9
+ int n = Integer .parseInt (scanner .nextLine ().trim ());
10
+ String output [] = new String [n ];
11
+ for (int i =0 ;i <n ;i ++){
12
+ String line = scanner .nextLine ();
13
+ output [i ] = isBalanced (line );
14
+ }
15
+ for (int i =0 ;i <n ;i ++)
16
+ System .out .println (output [i ]);
17
+ }
18
+
19
+ public static String isBalanced (String line ){
20
+ String output = null ;
21
+ ArrayList <Character > charStack = new ArrayList <>();
22
+ for (Character c : line .toCharArray ()){
23
+ if (c == '(' || c == '[' || c == '{' ){
24
+ charStack .add (c );
25
+ }else {
26
+ if (charStack .isEmpty ()){
27
+ output = "NO" ;
28
+ break ;
29
+ }
30
+ char ch = charStack .remove (charStack .size ()-1 );
31
+ if (c == ')' && ch == '(' ){
32
+ continue ;
33
+ }else if (c == '}' && ch == '{' ){
34
+ continue ;
35
+ }else if (c == ']' && ch == '[' ){
36
+ continue ;
37
+ }else {
38
+ output = "NO" ;
39
+ break ;
40
+ }
41
+ }
42
+ }
43
+
44
+ if (!charStack .isEmpty ())
45
+ output = "NO" ;
46
+ if (output == null )
47
+ output = "YES" ;
48
+
49
+ return output ;
50
+ }
51
+ }
52
+
53
+ /*
54
+
55
+ Input
56
+ 3
57
+ {[()]}
58
+ {[(])}
59
+ {{[[(())]]}}
60
+ {{}(
61
+
62
+ Output
63
+ YES
64
+ NO
65
+ YES
66
+ NO
67
+
68
+ */
You can’t perform that action at this time.
0 commit comments