-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedParenInExpression.java
More file actions
executable file
·94 lines (77 loc) · 2.42 KB
/
Copy pathBalancedParenInExpression.java
File metadata and controls
executable file
·94 lines (77 loc) · 2.42 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS info.picocli:picocli:4.5.0
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.concurrent.Callable;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import static picocli.CommandLine.Parameters;
import static java.lang.System.*;
/**
* https://www.youtube.com/watch?v=IhJGJG-9Dx8 {}, [], (). See if a given string is balanced or not.
* e.g. {()[{({})[]()}]}([])
*
* <p>BALANCED: {}()[{}] [({})] ({[]})
*
* <p>UNBALANCED: [({(}] ({[}) ()}[]
*/
@Command(
name = "BalancedParenInExpression",
mixinStandardHelpOptions = true,
version = "BalancedParenInExpression 0.1",
description = "Report if the given set of brackets is balanced or not")
class BalancedParenInExpression implements Callable<Integer> {
@Parameters(index = "0", arity = "0..*", description = "The string of brackets to evaluate.")
private String[] inputStrings;
private static HashMap<Character, Character> brackets = new HashMap<>(3);
static {
brackets.put('(', ')');
brackets.put('[', ']');
brackets.put('{', '}');
}
public static void main(String... args) {
int exitCode = new CommandLine(new BalancedParenInExpression()).execute(args);
System.exit(exitCode);
}
@Override
public Integer call() throws Exception {
if (inputStrings == null) {
inputStrings = new String[6];
// BALANCED:
inputStrings[0]="{}()[{}]";
inputStrings[1]="[({})]";
inputStrings[2]="({[]})";
// UNBALANCED:
inputStrings[3]="[({(}]";
inputStrings[4]="({[})";
inputStrings[5]="()}[]";
}
for (String str : inputStrings) {
printBalanced(str);
}
return 0;
}
private void printBalanced(String val) {
System.out.println(val + " is" + (isBalanced(val) == false ? " not " : " ") + "balanced");
}
private static boolean isOpenBracket(char c) {
return brackets.containsKey(c);
}
private static boolean isMatchingBracketType(char open, char close) {
return (brackets.get(open) == (close));
}
private static boolean isBalanced(String expression) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : expression.toCharArray()) {
if (isOpenBracket(c)) {
stack.push(c);
} else {
if (stack.isEmpty() || !isMatchingBracketType(stack.pop(), c)) {
return false;
}
}
}
return stack.isEmpty();
}
}