I have read this and I want to know how the solution that I came up with in my interview compares with the top solution.
public static String reverseWords(String s) {
if (s == null) return null;
else if (s.equals("")) return "";
else {
s = s.trim();
int index;
for (index = 0; index < s.length(); index++) {
if (s.charAt(index) == ' ') break;
}
String res = reverseWords(s.substring(index)) + " " + s.substring(0, index);
return res.trim();
}
}
My code is more space inefficient, as I was concatenating instead of appending, so I created many copies of new strings. What about time complexity though? They both seem to be in \$O(n)\$ time, but I'm not sure about the constant factors.
Also, how does split()
specifically perform against charAt()
? I knew about the split()
operation, but I opted for charAt()
because I thought that split()
was more expensive (wasn't sure; but I think it does some regex processing, which may be expensive). Should I have opted for split()
instead?