Recursively test if strings are palindromes - C++ Data Structure

C++ examples for Data Structure:Algorithm

Introduction

A palindrome is a string that is spelled the same way forward and backward.

Demo Code

#include <iostream>
#include <string>

bool testPalindrome(const std::string &, int);

int main(int argc, const char *argv[]) {
    std::string test1 = "not a palindrome";
    std::string test2 = "able was i ere i saw elba";
    std::string test3 = "stressed rats on paws swap no star desserts";

    std::cout << ((testPalindrome(test1, test1.length() - 1)) ? "TRUE: ": "FALSE: ") << test1 << std::endl;
    std::cout << ((testPalindrome(test2, test2.length() - 1)) ? "TRUE: " : "FALSE: ") << test2 << std::endl;
    std::cout << ((testPalindrome(test3, test3.length() - 1)) ? "TRUE: " : "FALSE: ")<< test3 << std::endl;

    return 0;/*w  w  w.j a v  a 2 s  .  c om*/
}
bool testPalindrome(const std::string &st, int end) {
    static int start = 0;

    if (start >= end) {
        start = 0;
        return true;
    }

    if (st[start] != st[end]) 
       return false;

    ++start;

    return testPalindrome(st, --end);
}

Related Tutorials