palindrome txt


//One way to create a palindrome text program is to use a recursive function that takes a string as its argument. The function will check if the string is a palindrome or not. If it is, it will return true, if not, it will return false.

//Recursive function to check if a string is a palindrome or not
function isPalindrome (txt) {
    //base case
    if (txt.length <= 1) return true;

    //check first and last character
    if (txt.charAt(0) !== txt.charAt(txt.length -1)) return false;

    //recursive call
    return isPalindrome( txt.substring(1, txt.length -1) );
}

//Test strings
console.log(isPalindrome("level"));
console.log(isPalindrome("abba"));
console.log(isPalindrome("abcd"));
    

This program uses a recursive function to check whether a given string is a palindrome or not. The function takes a string as its argument and checks if the string is a palindrome or not. If the string is a palindrome, the function returns true, and if not, the function returns false. The program checks the first and last characters of the string and, if they are the same, it makes a recursive call with a substring that excludes the first and last characters. The process is repeated until there is only one character left in the string. If all the characters from the beginning and end of the string are the same, the string is a palindrome. The program is tested with three strings, two of which are palindromes, and one which is not. The output is as expected, with "level" and "abba" returning true, and "abcd" returning false.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe