Write a recursive method called isReverse that accepts two strings as parameters and returns true if the two strings contain the same sequence of characters as each other but in the opposite order (ignoring capitalization), and false otherwise. For example, the call of isReverse("hello", "eLLoH") would return true. The empty string, as well as any one-letter string, is considered to be its own reverse
package recursion;
public class ReverseCompare {
// this method takes two string arguments
public static boolean isReverse(String string1, String string2) {
// if lengths of both strings are not same return false
if (string1.length() != string2.length())
return false;
// if both are empty strings return true
if (string1.length() == 0 && string2.length() == 0)
return true;
// acc to question if both strings length is 1 return true
if (string1.length() == 1 && string2.length() == 1)
return true;
char char1 = Character.toLowerCase(string1.charAt(0));
char char2 = Character.toLowerCase(string2.charAt(string2.length() - 1));
// substring() returns the string starting from index we passed in it
String sub1 = string1.substring(1);
//this substring method takes two arguments start index and end index and make
// create substring out of it
String sub2 = string2.substring(0, string2.length() - 1);
return char1 == char2 && isReverse(sub1, sub2);
}
public static void main(String[] args) {
String string1 = "nano";
String string2 = "onan";
System.out.print("are " + string1 + " and " + string2 + " are reverse of each other? ");
System.out.println(isReverse(string1, string2));
}
}
Output:
are nano and onan are reverse of each other? true