1
1
package Stack ;
2
2
3
3
4
+ import java .util .Stack ;
5
+
4
6
public class BalancedParanthesisUsingStack {
5
7
8
+ /***
9
+ * Algorithm :
10
+ * @return boolean
11
+ * 1. Define a Stack
12
+ * 2. scan the String and parse the brackets
13
+ * 3. if the bracket is left bracket it means another bracket suppose to
14
+ * complete it. keep pushing into the stack
15
+ *
16
+ * 4. if it's a right bracket check if the top item in the stack equals its reverseBracket
17
+ * 5. if it is not equal or if stack is empty , it means they are not balanced
18
+ * 6. After parsing , if the stack is empty , then brackets are balanced
19
+ */
20
+ public static boolean isBracketBalanced (String str ) {
21
+
22
+ Stack <Character > stack = new Stack <>();
23
+ char [] bracket = str .toCharArray ();
24
+
25
+ for (char ch : bracket ) {
26
+
27
+ char reverseBracket = getReverseBracket (ch );
28
+ if (ch == '{' || ch == '[' || ch == '(' ) {
29
+ stack .push (ch );
30
+ }
31
+ else if (stack .isEmpty () || stack .pop () != reverseBracket ) {
32
+ return false ;
33
+ }
34
+ }
35
+
36
+ return stack .isEmpty ();
37
+ }
38
+
39
+ public static char getReverseBracket (char ch ) {
40
+ if (ch == '{' ) {
41
+ return '}' ;
42
+ }
43
+ else if (ch == '[' ) {
44
+ return ']' ;
45
+ }
46
+ else if (ch == '(' ) {
47
+ return ')' ;
48
+ }
49
+ else if (ch == '}' ) {
50
+ return '{' ;
51
+ }
52
+ else if (ch == ']' ) {
53
+ return '[' ;
54
+ }
55
+ else {
56
+ return '(' ;
57
+ }
58
+ }
59
+
6
60
public static void main (String [] args ) {
7
- // yet to implement
61
+
62
+ String test1 = "{([])}" ;
63
+ String test2 = "{([)}" ;
64
+ String test3 = "{([])" ;
65
+ String test4 = "{[()]}" ;
66
+
67
+ System .out .println (isBracketBalanced (test1 )); // true
68
+ System .out .println (isBracketBalanced (test2 )); // false
69
+ System .out .println (isBracketBalanced (test3 )); // false
70
+ System .out .println (isBracketBalanced (test4 )); // true
71
+
8
72
}
9
73
10
- }
74
+ }
0 commit comments