Tim Carew Tim Carew - 1 month ago 7
Java Question

Using recursion to test if two strings are the same but reversed

For my assignment I have to use recursion to test if two strings are the same but reversed.

Here is the actual question:

Write a recursive method called isStringReversed which, given two String parameters, returns true if the two strings contain the same sequence of characters but in reverse order (ignoring capitalization), and false otherwise. For example, isStringReversed("piano", "oNaIp") would return true. Note: the null (empty) string and string of one letter are both the reverse of themselves.

Here's what I have made, but when I execute the program, i always get
a false return. Heres my code:

public static boolean isStringReversed(String s1, String s2)
{
if (s1 == null || s2 == null || s1.length() == 1 || s2.length() == 1)
{
return true;
}

else if (s1.length() != s2.length())
{
return false;
}

else
{
char s1first = Character.toLowerCase(s1.charAt(0));
char s2last = Character.toLowerCase(s2.charAt(s2.length() - 1));

if (s1first == s2last)
{
String s1shorter = s1.substring(0, s1.length() - 1);
String s2shorter = s2.substring(0, s2.length() - 1);
return isStringReversed(s1shorter, s2shorter);
}
else
{
return false;
}


}




}

Answer

Instead of

    String slshorter = sl.substring(0, s1.1ength() - l) ;
    String s2shorter = s2.substring(0, s2.1ength() - l) ;

use

    String slshorter = sl.substring(1) ;
    String s2shorter = s2.substring(0, s2.1ength() - 1) ;

Note that the second parameter of the method substring() means to that index exclusive.

Comments