File tree 1 file changed +54
-0
lines changed
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Author: Atharv Damle
2
+ // Use a stack to see if paranthesis in a String is balanced.
3
+ // Full Question: https://www.hackerrank.com/challenges/java-stack/problem
4
+
5
+ // Logic: Add the opening brackets in a stack. Remove the top bracket if its match is found.
6
+ // If the stack is empty at the end of the string, it is balanced (as all brackets are now in pairs), else it is not.
7
+
8
+ import java .util .*;
9
+ class JavaStack
10
+ {
11
+ public static void main (String []args )
12
+ {
13
+ Scanner sc = new Scanner (System .in );
14
+
15
+ while (sc .hasNext ()) {
16
+ String input =sc .next ();
17
+ int l = input .length ();
18
+
19
+ // Deque is the recommended Java implementation of stack. It will take in Character type data
20
+ Deque <Character > s = new ArrayDeque <>();
21
+
22
+ for (int i = 0 ; i < l ; i ++)
23
+ {
24
+ char ch = input .charAt (i );
25
+
26
+ // peek() function returns the next element that can be removed from the stack
27
+ // Pairs of brackets have a maximum difference of 2. (According to the ASCII Table)
28
+ if (!s .isEmpty () && ((s .peek () == ch - 1 ) || (s .peek () == ch - 2 )))
29
+ {
30
+ // Remove element from top of stack
31
+ s .removeFirst ();
32
+ }
33
+ else
34
+ {
35
+ // Add element to the top of stack.
36
+ s .addFirst (ch );
37
+ }
38
+ }
39
+
40
+ // If the stack is not empty...
41
+ if (!s .isEmpty ())
42
+ {
43
+ System .out .println (false );
44
+ }
45
+ else
46
+ {
47
+ System .out .println (true );
48
+ }
49
+ }
50
+ }
51
+ }
52
+
53
+
54
+
You can’t perform that action at this time.
0 commit comments