Last active
October 18, 2018 19:51
-
-
Save pluto-atom-4/1889be2b0032688e9414d21bbb951db1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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