Skip to content

Instantly share code, notes, and snippets.

@pluto-atom-4
Last active October 18, 2018 19:51
Show Gist options
  • Save pluto-atom-4/1889be2b0032688e9414d21bbb951db1 to your computer and use it in GitHub Desktop.
Save pluto-atom-4/1889be2b0032688e9414d21bbb951db1 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
class BracketMatch {
static int bracketMatch(String text) {
if (text == null || text.isEmpty()) {
throw new IllegalArgumentException("Provide a text");
}
if (!text.replaceAll("[()]", "").isEmpty()) {
throw new IllegalArgumentException("Found invalid character");
}
int count = 0;
int orphanCloseBracket = 0;
for (int idx = 0; idx < text.length(); idx++) {
if (text.charAt(idx) == '(') {
count++;
} else {
if (count == 0) {
orphanCloseBracket++;
} else if (count > 0 ) {
count--;
}
}
}
return count+orphanCloseBracket;
}
public static void main(String[] args) {
System.out.println(bracketMatch("(()")); // 1
System.out.println(bracketMatch("(())")); // 0
System.out.println(bracketMatch("())(")); // 2
}
}
/*
text = "())("
n=0
---------+
(| push
---------+
n=1
---------+
| pop
---------+
n=2
---------+
| orphanCloseBracket : 1
---------+
n=3
---------+
)| push
---------+
openBracketSize: 1
text = "(())"
n=0
---------+
(| push
---------+
n=1
---------+
((| push
---------+
n=2
---------+
(| pop
---------+
n=3
---------+
| pop
---------+
openBracketSize: 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment