Any other way to Reverse String Without using array?

#include <string>
#include <algorithm>
#include <iostream>

int main()
{
    std::string s;
    getline(std::cin, s);

    if (std::equal(s.begin(), s.end(), s.rbegin()))
        std::cout << s << " is a palindrome\n";
    else
        std::cout << s << " is not a palindrome\n";
}

No arrays, no pointers.


bool is_palindrome(const char* s)
{
    const char *p = s;
    const char *q = s + strlen(s) - 1;
    while (p < q) {
        if (*p != *q)
            return false;
        ++p;
        --q;
    } 
    return true;
}

My solution: (not that effiecient though, but just yet another "different" solution)

bool is_palindrome(const std::string& s) 
{
   struct local
   {
        static bool work(const std::string& s, int l, int h) 
        {
           return l>= h? true: (s[l] == s[h]? work(s, l + 1, h -1): false);
        }
    };
    return local::work(s, 0, s.size() - 1);
}

//usage
cout << is_palindrome("liril"); //just pass one argument. that's it!

Demo : http://www.ideone.com/WNuEC

Tags:

Algorithm

C++