Anirudh Anirudh - 2 months ago 23
Java Question

Alternate Solution for maxBlock from CodingBat

Solving this problem from codingBat


Given a string, return the length of the largest "block" in the
string. A block is a run of adjacent chars that are the same.

maxBlock("hoopla") → 2


maxBlock("abbCCCddBBBxx") → 3


maxBlock("") → 0



I was trying to solve it using one for loop as below:

public int maxBlock(String str) {
int maxCounter=1;
int counter=1;
if(str.length()==0)
{
return 0;
}
for(int i=0;i<str.length()-1;i++)
{
if(str.substring(i,i+1).equals(str.substring(i+1,i+2)))
{
counter++;

}
if(counter>maxCounter)
{
maxCounter=counter;
counter=0;
}
}


return maxCounter;
}


It beats all the cases apart from one. Can anybody show a solution with one for loop?

Sorry for mentioning late but you can't use REGEX or anything from collections framework.

Answer

I think you get it wrong in certain edge cases:

public int yourMaxBlock(String str) {
    int maxCounter = 1;
    int counter = 1;
    if (str.length() == 0) {
        return 0;
    }
    for (int i = 0; i < str.length() - 1; i++) {
        if (str.substring(i, i + 1).equals(str.substring(i + 1, i + 2))) {
            counter++;

        }
        if (counter > maxCounter) {
            maxCounter = counter;
            counter = 0;
        }
    }

    return maxCounter;
}

public int myMaxBlock(String str) {
    int maxCounter = 1;
    int counter = 1;
    if (str.isEmpty()) {
        return 0;
    }
    for (int i = 1; i < str.length(); i++) {
        if (str.charAt(i - 1) == str.charAt(i)) {
            if (++counter > maxCounter) {
                maxCounter = counter;
            }
        } else {
            counter = 1;
        }
    }

    return maxCounter;
}

public void test() {
    String[] tests = new String[]{
        "", "+", "++", "+++,++,++,+", "+,++,+++,++,", "+,++,+++,++++", "+++++,++,+++,++++"
    };
    for (String s : tests) {
        int myMax = myMaxBlock(s);
        int yourMax = yourMaxBlock(s);
        System.out.println("myMaxBlock(" + s + ") = " + myMax + (myMax != yourMax ? " WRONG! you have " + yourMax : ""));
    }
}

prints

myMaxBlock() = 0
myMaxBlock(+) = 1
myMaxBlock(++) = 2
myMaxBlock(+++,++,++,+) = 3
myMaxBlock(+,++,+++,++,) = 3
myMaxBlock(+,++,+++,++++) = 4 WRONG! you have 3
myMaxBlock(+++++,++,+++,++++) = 5 WRONG! you have 4