@HenningMakholm's answer is excellent, but I just wanted to throw it away based on the comment about iterative methods and immutable strings from @cHao. This would probably be most suitable for comment, but I wanted space real estate to respond ...
public static String reverse3(String str){ StringBuilder sb = new StringBuilder(); int i; for(i = str.length() - 1; i >= 0; i--) { sb.append(str.charAt(i)); } return sb.toString(); }
This iterative method, which at the end creates only one immutable String object and works in O(n) , gives the following results:
Length: 5406 Reverse 1: 10811 function calls 59 milliseconds 5406 length correctness test Reverse 2: 5406 function calls 126 milliseconds 5406 length correctness test Reverse 3: 3 milliseconds 5406 length correctness test
durron597
source share