Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
- */
Add Comment
Please, Sign In to add comment