Update ReverseString.java

Using recursion for reversing a String serves us no benifit. It places extra load on the stack, and it is less efficient than doing so iteratively. I understand now that we can not use built in reverse function, but using recursion is still the worst way we could do the task of String reversal. Everytime we call the reverse method we are placing an extra frame on our stack. This uses space. We also create another string that we are appending our result to with the recursive solution, which is slow because under the hood, Java will create a new empty String and then append each character to the new String, one char at a time. If we do this for each character, then asymtotically we now have time complexity of O(n^2).  Recursion in this case also does not make our solution "simpler" or "more elegant". We want to use recursion when it is advantageous to do so....like traversing trees
This commit is contained in:
MarcHines 2017-06-01 08:09:19 -04:00 committed by GitHub
parent 6ff4a1fb6f
commit 066dd615a6

View File

@ -16,19 +16,17 @@ class ReverseString
* @param str String to be reversed
* @return Reversed string
*/
static String reverseString(String str)
{
String reverse="";
if(str.length()==1)
{
return str;
}
else
{
reverse=reverse+str.charAt(str.length()-1)+reverseString(str.substring(0,str.length()-1));
return reverse;
}
}
public static String reverse(String str){
if(str.isEmpty() || str == null) return str;
char arr[] = str.toCharArray();
for(int i = 0, j = str.length() - 1; i < j; i++, j--){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return new String(arr);
}
/**
* Main Method
@ -45,4 +43,4 @@ class ReverseString
br.close();
}
}