I am trying to write a recursion to reverse a String.This is my approach.
public static void main(String[] args) { String str = "abc"; String b = reverseString(str); System.out.println(b); } public static String reverseString(String a){ if (a.isEmpty()){ return a; } return reverseString(a.substring(1)) + a.charAt(0); }
I dont get why when it reaches the base case, where my a is already empty but I am still able to print out the reversed string.
Advertisement
Answer
you are not implementing any recursion, you just replaced two halves of a string.
public static void main(String[] args) { String str = "abcd"; String b = reverseString(str); System.out.println(b); } public static String reverseString(String str) { int p = str.length() / 2; if (str.length() == 1) return str; String prefix = reverseString(str.substring(p, str.length())); String suffix = reverseString(str.substring(0, p)); return prefix + suffix; }