In: Computer Science
Write a java program with 3 recursive methods that reverse the order of a string. The first recursive method should reverse the order starting from the left selecting the leftmost character as the head and the remaining part of the string as its tail., the second starting from the right selecting the rightmost character as the head and the remaining part of the string on its left as the tail, and the last a recursive method starting from the middle by extract two characters simultaneously from both left and right.
import java.util.Scanner; public class ReverseString { public static String reverseString(String s) { if (s.isEmpty()) { return ""; } else { return reverseString(s.substring(1)) + s.charAt(0); } } public static String reverseString2(String s) { if (s.isEmpty()) { return ""; } else { return s.charAt(s.length()-1) + reverseString2(s.substring(0, s.length()-1)); } } public static String reverseString3(String s) { if (s.length() <= 1) { return s; } else { return s.charAt(s.length()-1) + reverseString3(s.substring(1, s.length()-1)) + s.charAt(0); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a string: "); String line = in.nextLine(); System.out.println(reverseString(line)); System.out.println(reverseString2(line)); System.out.println(reverseString3(line)); } }