-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedParenthesisChecker.java
More file actions
36 lines (30 loc) · 935 Bytes
/
Copy pathBalancedParenthesisChecker.java
File metadata and controls
36 lines (30 loc) · 935 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
35
36
public class BalancedParenthesisChecker {
public static boolean isBalanced (String expString) {
Stack stack = new Stack(expString.length());
for (int i = 0; i < expString.length(); i++) {
char ch = expString.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.is_empty()){
return false;
}
char top = (Character)stack.pop();
if(!isMatchingPair(top,ch)) {
return false;
}
}
}
return stack.is_empty();
}
private static boolean isMatchingPair(char open, char close) {
if (open == '(' && close == ')') {
return true;
} else if (open == '{' && close == '}') {
return true;
} else if (open == '[' && close == ']') {
return true;
}
return false;
}
}