066dd615a6
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
47 lines
1.1 KiB
Java
47 lines
1.1 KiB
Java
import java.io.BufferedReader;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
|
|
/**
|
|
* This method produces a reversed version of a string
|
|
*
|
|
* @author Unknown
|
|
*
|
|
*/
|
|
class ReverseString
|
|
{
|
|
|
|
/**
|
|
* This method reverses the string str and returns it
|
|
* @param str String to be reversed
|
|
* @return Reversed string
|
|
*/
|
|
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
|
|
*
|
|
* @param args Command line arguments
|
|
* @throws IOException Exception thrown because of BufferedReader
|
|
*/
|
|
public static void main(String args[]) throws IOException
|
|
{
|
|
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
|
|
System.out.println("Enter the string");
|
|
String srr=br.readLine();
|
|
System.out.println("Reverse="+reverseString(srr));
|
|
br.close();
|
|
}
|
|
}
|
|
|