SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Recursion
Exercise:
Exercises
Question:11 | ISBN:9780136091813 | Edition: 2

Question

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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.