33.3k views
1 vote
Write a recursive algorithm to check if two strings have the same characters but in reverse order.

1 Answer

3 votes

Final answer:

A recursive algorithm can be used to check if two strings have the same characters but in reverse order.

Step-by-step explanation:

A recursive algorithm can be used to check if two strings have the same characters but in reverse order. Here is an example of a recursive algorithm in Python:

def check_reverse(str1, str2):
# Base case
if len(str1) != len(str2):
return False
if len(str1) == 0:
return True

# Recursive case
if str1[0] == str2[-1]:
return check_reverse(str1[1:], str2[:-1])
else:
return False

# Example usage
def main():
string1 = "hello"
string2 = "olleh"

if check_reverse(string1, string2):
print("The two strings have the same characters in reverse order")
else:
print("The two strings do not have the same characters in reverse order")

main()

This implementation checks if the lengths of the two strings are equal. It then checks if the first character of the first string matches the last character of the second string. If they do, it calls the function recursively with the remaining strings. If at any point the characters don't match, it returns False. If the strings become empty, it returns True.

User Aylen
by
8.7k points