Nico Nico - 6 months ago 24
Java Question

CodingBat sameEnds dealing with Strings

I'm trying to do this problem from CodingBat
but don't understand why it doesn't work with input string "Hello!".

This is my code and below my code are the results I'm getting.

public String sameEnds(String string) {
String result;
int strLen = string.length();
boolean isOdd = (strLen % 2 != 0);
String start = string.substring(0, strLen / 2);
String end;
if (isOdd) {
end = string.substring(strLen / 2 + 1);
} else {
end = string.substring(strLen / 2);
}
int i = 0;
while (!start.equals(end) && i <= start.length()) {
start = start.substring(0, start.length() - i);
end = end.substring(i, end.length());
i++;
}
if (start.equals(end)) {
result = start;
} else {
result = "";
}
return result;
}


Results I'm getting

Answer

Your problem is that you are both incrementing i and using start.length()-i. When i is equal to 1, the start variable becomes one character shorter. But when i is 2, start.length() is already one less than the original, and now you subtract 2 characters, so now you've missed one. The same is true for the end variable. Don't use both an incrementing i and the changing length of the strings.

To fix it, don't change the original start and end variables. Do something like this:

    String sTmp = start;
    String eTmp = end;
    while (!sTmp.equals(eTmp) && i <= start.length()) {
        sTmp = start.substring(0, start.length() - i);
        eTmp = end.substring(i, end.length());
        i++;
    }
    if (sTmp.equals(eTmp)) {
        result = sTmp;
    } else {
        result = "";
    }
    return result;
Comments