I am going through the Java CodingBat exercises. Here is the one I have just completed:
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".]
Here is my code:
public String sameEnds(String string) {
int strLength = string.length();
if (string.substring(0, strLength/2).equals(string.substring(strLength/2, strLength))) {
return string.substring(0, strLength/2);
}
for (int i = 1; i < strLength; i++) {
if (string.substring(0, i).equals(string.substring(strLength-i, strLength) )) {
return string.substring(0, i);
}
}
return "";
}
The code passes the majority of the tests without the first if
statement, so that was included to ensure it passes circumstances such as an input of xxxx
. Without this statement, xxxx
returns x
, which is incorrect.
My questions are:
- Is it acceptable/correct to use this 'cautionary'
if
statement, or should I somehow be incorporating it into thefor
loop? - Would it make sense, for readability and conciseness, to be creating some variables for things like
string.substring()
, as I did withstrLength
? - Would it make sense to use a
StringBuilder
? I can't really see how it could be used in this particular case. Does it make sense to use separate
return
statements, or would it be more useful to assign the outcome to a resultantstring
, and use only onereturn
statement at the end of the method? i.e.:Separate statements of
String result = "result here";
.One statement at the bottom of
return result;
.