-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVaildParenthesis.java
More file actions
34 lines (29 loc) · 942 Bytes
/
VaildParenthesis.java
File metadata and controls
34 lines (29 loc) · 942 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Stack;
public class VaildParenthesis {
public static boolean isBalanced(String s) {
Stack<Character> stk = new Stack<>();
for(char c: s.toCharArray()) {
if(c=='(' || c=='{' || c =='[') {
stk.push(c);
}
else if(c == ')' || c == '}' || c == ']') {
//No opening Bracket or empty stack
if(stk.isEmpty()) {
return false;
}
char top = stk.peek();
if((c==')' && top !='(') ||
(c=='}' && top !='{') ||
(c==']' && top !='[')) {
return false;
}
stk.pop();
}
}
return stk.isEmpty();
}
public static void main(String[] args) {
String s = "[()()]{}";
System.out.println((isBalanced(s)? "true": "false"));
}
}