Skip to content

Commit 44fd301

Browse files
authored
Create BalancedParetheses.java
1 parent 2471538 commit 44fd301

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Medium/BalancedParentheses

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy