In: Computer Science
1. Obtain the following string: abcdefghijklmnopqrstuvwxyz (as input or using initialization)
2. Using recursion, write a reverse function that reverses the characters in a string or character array given two indices (starting and ending). The string or the character array should reflect the reversal.
3. Read indices as input 11,18 (i.e. letters 12,19)
4. Call the reverse function to reverse letters: 12-19
5. Read indices as input 4,22 (i.e. letters 5,23)
6. Call the reverse function to reverse letters: 5,23
7. Using the reverse function, reverse the alphabet 8. Print the reversed string or character array.
Your output should contain:
abcdefghijksrqponmltuvwxyz
abcdwvutsrqponmlkjihgfexyz
zyxwvutsrqponmlkjihgfedcba
NOTE: your recursive function should modify the original string passed in as an argument, NOT make additional copies of the original string
import java.util.*;
public class Main
{
static void reverseString(char[] ch,int i,int j)
{
if (i >=j) //recursively goes until i becomes greater than
j
return;
swap(ch,i,j); //swap first index and last index
reverseString(ch, i + 1,j-1); //incr && decr index call
recursion
}
static char[] swap(char []arr, int i, int j)
{
char temp= arr[i]; //swapping Characters
arr[i]=arr[j];
arr[j]=temp;
return arr;
}
public static void main(String[] args) {
String str="abcdefghijklmnopqrstuvwxyz";
int n = str.length();
int i,j;
char []ch = str.toCharArray();
Scanner s=new Scanner(System.in);
for(int k=0;k<2;k++){
i=s.nextInt();
j=s.nextInt();
reverseString(ch, i,j);
System.out.println(ch);
}
}
}