File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package AlgoExpert_Medium;
2
+
3
+ import java.util.Deque;
4
+ import java.util.HashMap;
5
+ import java.util.List;
6
+ import java.util.Map;
7
+ import java.util.ArrayDeque;
8
+ import java.util.ArrayList;
9
+
10
+ public class BalancedBrackets {
11
+
12
+ public static void main(String[] args) {
13
+
14
+ System.out.println(balancedBrackets("()()[{()})]")); // ")[]}"
15
+
16
+ }
17
+
18
+ public static boolean balancedBrackets(String str) {
19
+
20
+ Deque<Character> stack = new ArrayDeque<>();
21
+ List<Character> closing = new ArrayList<>() ;
22
+ closing.add('}'); closing.add(')'); closing.add(']') ;
23
+
24
+ Map<Character, Character> map = new HashMap<>() ;
25
+ map.put('{' , '}') ;
26
+ map.put('(' , ')') ;
27
+ map.put('[' , ']') ;
28
+
29
+
30
+ for(int i=0; i < str.length() ; i++ ) {
31
+
32
+ if(closing.contains(str.charAt(i))) {
33
+
34
+ if(!stack.isEmpty() && str.charAt(i) == map.get(stack.peek() )) {
35
+ stack.pop();
36
+ continue;
37
+ } else {
38
+ return false ;
39
+ }
40
+
41
+ }
42
+ else {
43
+ stack.push(str.charAt(i));
44
+ }
45
+ }
46
+
47
+ System.out.println(stack.size());
48
+
49
+ if(stack.isEmpty()) {
50
+ return true ;
51
+ } else {
52
+ return false;
53
+ }
54
+ }
55
+
56
+ }
You can’t perform that action at this time.
0 commit comments