Is palindrome (recursion)
Given a string, write a method that checks if it is a palindrome. String length may be >= 0.
Expected input and output
IsPalindromeRecursion("xx") → true
IsPalindromeRecursion("pendrive") → false
using System;
namespace CSharpExercises.Exercises.Recursion
{
class IsPalindromeRecursionTask
{
static bool IsPalindromeRecursion(string str)
{
if (str.Length == 1 || (str.Length == 2 && str[0] == str[1]))
{
return true;
}
else if (str.Length > 1)
{
if (str[0] != str[str.Length - 1])
{
return false;
}
return IsPalindromeRecursion(str.Substring(1, str.Length - 2));
}
return false;
}
static void Main(string[] args)
{
Console.WriteLine(IsPalindromeRecursion("aa")); // True
Console.WriteLine(IsPalindromeRecursion("dad")); // True
Console.WriteLine(IsPalindromeRecursion("apple")); // False
Console.WriteLine(IsPalindromeRecursion("deleveled")); // True
Console.WriteLine(IsPalindromeRecursion("")); // False
Console.WriteLine(IsPalindromeRecursion("hannah")); // True
Console.WriteLine(IsPalindromeRecursion("X")); // True
}
}
}