-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalanceParentheses.java
More file actions
44 lines (35 loc) · 1.11 KB
/
BalanceParentheses.java
File metadata and controls
44 lines (35 loc) · 1.11 KB
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
37
38
39
40
41
42
43
44
package learn.ds.stack;
import java.util.Stack;
/**
* @author Varma Penmetsa
*
* https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
*/
public class BalanceParentheses {
public static boolean checkBalance(String s) {
if (s.length() == 0 || s.length() % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<Character>();
char[] c = s.toCharArray();
if (c[0] == ']' || c[0] == '}' || c[0] == ')') {
return false;
}
for (int i = 0; i < c.length; i++) {
if (c[i] == '{') {
stack.push('}');
} else if (c[i] == '(') {
stack.push(')');
} else if (c[i] == '[') {
stack.push(']');
// checking st.isEmpty in cases where the char arrays just contains ')}]'
} else if (stack.isEmpty() || c[i] != stack.pop()) {
return false;
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(checkBalance("[()]"));
}
}