-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBalancedChars.java
62 lines (51 loc) · 1.44 KB
/
BalancedChars.java
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package nyc.c4q.jrod;
import java.util.Stack;
public class BalancedChars {
public static void main(String[] args) {
testBalancedChars("");
testBalancedChars("([{}])");
testBalancedChars("{[}]");
testBalancedChars("(([])))");
testBalancedChars("()[{}]");
testBalancedChars("((())");
}
private static void testBalancedChars(String s) {
System.out.printf("is '%s' balanced?: %b\n", s, isBalanced(s));
}
private static boolean isBalanced(String s) {
if(s.isEmpty()) return true;
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(isLeftChar(c)) {
stack.push(c);
}
else if(isRightChar(c)){
if(stack.isEmpty()) {
return false;
}
char leftChar = stack.pop();
if(!isMatchingPair(leftChar, c)) {
return false;
}
}
else {
return false; // invalid char
}
}
// no failures up to now
// but first make sure we don't have extra left chars
return stack.isEmpty();
}
private static boolean isMatchingPair(char lc, char rc) {
return (lc == '{' && rc == '}') ||
(lc == '(' && rc == ')') ||
(lc == '[' && rc == ']');
}
private static boolean isRightChar(char c) {
return c == '}' || c == ')' || c == ']';
}
private static boolean isLeftChar(char c) {
return c == '{' || c == '(' || c == '[';
}
}