I'll accept both solutions. In fact, I think your own solution is arguably easier to read, if you drop the else
and rename your temporary variable:
if (word.length() < 2) {
return word;
}
int lastIndex = word.length() - 1;
return word.charAt(lastIndex) + reverse(word.substring(0, lastIndex));
That can be read as "get the character at lastIndex
, and append the reverse of the word
from the start to just before lastIndex
". This literally chains my train of thought on lastIndex
as the anchor point of doing the reversal. Given the left-to-right reading style for English, this 'shifting right' idea is intuitive.
Compare this with the suggest answer, which I will attempt to read as "get the reverse of the word
from the second character onwards, and append the first character at the end". The idea of doing the reversal by 'shifting left' is not well-contained as a form of mental evaluation (for English).
If one is splitting hairs though, the suggested answer can be faster, but at this point we're really talking about micro-optimizations here (e.g. performing the reversal 10000 times on 1000-character String
s). It doesn't require the computation of word.length() - 1
, and the implementation of String.substring(int)
is slightly simpler compared to String.substring(int, int)
.
Unless there is a real performance concern for what you say are only recursion exercises, I'll say this is not something to be overly concerned about, and your own solution is good enough.