summaryrefslogtreecommitdiff
path: root/src/main
diff options
context:
space:
mode:
authorHaidong Ji2019-01-01 21:08:58 -0600
committerHaidong Ji2019-01-01 21:08:58 -0600
commita318045cf5c15cadad5c067ab6af5aa498bd155e (patch)
tree6bc0e84ffb77ec470065bacbffb639ae1ce78cd6 /src/main
Check bracket done!
Switching from Eclipse to Jetbrains IDEA, still using TDD methods. So far not bad. I like the fact that by using different IDEs, I can see what kind of help the IDE provides (coding style, best practices, etc.). That can be helpful.
Diffstat (limited to 'src/main')
-rw-r--r--src/main/Bracket.java51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/main/Bracket.java b/src/main/Bracket.java
new file mode 100644
index 0000000..e76eeba
--- /dev/null
+++ b/src/main/Bracket.java
@@ -0,0 +1,51 @@
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Arrays;
+import java.util.Stack;
+
+public class Bracket {
+
+ static String checkBracket(String exp) {
+ Stack<Character> charStack = new Stack<>();
+ int unmatchedOpeningBracket = 0;
+ int count = 0;
+ for (int i = 0; i < exp.length(); i++) {
+ char c = exp.charAt(i);
+ if (!Arrays.asList('[', ']', '(', ')', '{', '}').contains(c)) {
+ count = count + 1;
+ continue;
+ }
+
+ if (c == '[' || c == '(' || c == '{') {
+ charStack.push(c);
+ count = count + 1;
+ unmatchedOpeningBracket = count;
+ } else {
+ if (charStack.empty())
+ return Integer.toString(i + 1);
+ char top = charStack.pop();
+ if ((top == '[' && c != ']') || (top == '(' && c != ')') || (top == '{' && c != '}')) {
+ return Integer.toString(i + 1);
+ } else {
+ unmatchedOpeningBracket = unmatchedOpeningBracket - 1;
+ }
+ count = count + 1;
+ }
+ }
+ if (charStack.empty())
+ return "Success";
+ else if (unmatchedOpeningBracket > 0) {
+ return Integer.toString(unmatchedOpeningBracket);
+ }
+ return Integer.toString(count);
+ }
+
+ public static void main(String[] args) throws IOException {
+ InputStreamReader input_stream = new InputStreamReader(System.in);
+ BufferedReader reader = new BufferedReader(input_stream);
+ String text = reader.readLine();
+
+ System.out.println(checkBracket(text));
+ }
+}