package nl.dvberkel.dyck;

public class Checker {
    private final String left;
    private final String right;

    public Checker() {
        this("1", "2");
    }

    public Checker(String left, String right) {

        this.left = left;
        this.right = right;
    }

    public boolean check(String word) {
        boolean valid = imbalance(word) == 0;
        int prefixLength = word.length() - 1;
        while (valid && prefixLength > 0) {
            String prefix = word.substring(0, prefixLength);
            valid = imbalance(prefix) >= 0;
            prefixLength--;
        }
        return valid;
    }

    protected int imbalance(String word) {
        return count(word, left) - count(word, right);
    }

    private int count(String word, String substring) {
        int count = 0;
        for (int index = 0; index < word.length(); index++) {
            if (word.substring(index, index + substring.length()).equals(substring)) {
                count++;
            }
        }
        return count;
    }
}

@@ -20,16 +20,103 @@
 .dyck;%0A%0A
+import java.util.Iterator;%0A%0Aimport static nl.dvberkel.dyck.PrefixIterator.prefixesOf;%0A%0A
 public c
@@ -410,25 +410,60 @@
     
-boolean valid = i
+return noImbalance(word) && prefixesHaveNonNegativeI
 mbal
@@ -476,101 +476,172 @@
 ord)
- == 0
 ;%0A    
+%7D%0A%0A
     
-int prefixLength = word.length() - 1
+private boolean noImbalance(String word) %7B%0A        return imbalance(word) == 0
 ;%0A    
+%7D%0A%0A
     
-while (valid && prefixLength %3E 0
+private boolean prefixesHaveNonNegativeImbalance(String word
 ) %7B%0A
@@ -648,20 +648,21 @@
         
-    
+for (
 String p
@@ -671,42 +671,29 @@
 fix 
-= word.substring(0, prefixLength);
+: prefixesOf(word)) %7B
 %0A   
@@ -705,16 +705,12 @@
     
-valid = 
+if (
 imba
@@ -727,13 +727,14 @@
 ix) 
-%3E= 0;
+%3C 0) %7B
 %0A   
@@ -746,24 +746,30 @@
     
-prefixLength--;%0A
+    return false;%0A    
     
@@ -766,32 +766,42 @@
 ;%0A            %7D%0A
+        %7D%0A
         return v
@@ -803,13 +803,12 @@
 urn 
-valid
+true
 ;%0A  
@@ -1223,8 +1223,542 @@
     %7D%0A%7D%0A
+%0Aclass PrefixIterator implements Iterator%3CString%3E %7B%0A    public static Iterable%3CString%3E prefixesOf(String word) %7B%0A        return () -%3E new PrefixIterator(word);%0A    %7D%0A%0A    private final String word;%0A    private int prefixLength;%0A%0A    private PrefixIterator(String word) %7B%0A        this.word = word;%0A        this.prefixLength = word.length() - 1;%0A    %7D%0A%0A    @Override%0A    public boolean hasNext() %7B%0A        return prefixLength %3E 0;%0A    %7D%0A%0A    @Override%0A    public String next() %7B%0A        return word.substring(0, prefixLength--);%0A    %7D%0A%7D

Clean up Checker