Given task sameEnds from CodingBat:
Given a string, return the longest substring that appears at both the beginning and end of the string without overlapping. For example, sameEnds("abXab") is "ab".
sameEnds("abXYab") → "ab"
sameEnds("xx") → "x"
sameEnds("xxx") → "x"
My solution passes all the tests except one^:
public String sameEnds(String string) {
String substringFront = "";
String substringEnd = "";
String longestSubstring = "";
for (int i = 1; i < string.length() - 1; i++) {
substringFront = string.substring(0, i);
substringEnd = string.substring(i);
if (substringEnd.contains(substringFront)) {
longestSubstring = substringFront;
}
}
return longestSubstring;
}
What is the problem here? How could I fix it?

In addition to the technical issues that @Dan and others have aptly pointed out, I want to highlight the issue of unnecessary complexity, which in many cases leads to such logical errors.
Given this, and considering that this is a challenge, I would prefer a minimalistic approach, like the one below, which is self-explanatory and hence simple to comprehend and debug.
public String sameEnds(String string) {
int middle = string.length() / 2;
for (int i = middle; i >= 0; i--) {
String left = string.substring(0, i);
if (string.endsWith(left)) {
return left;
}
}
return "";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With