Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Algorithmically Simple Recursive Palindrome Checker

Tags:

c++

recursion

I wrote a string palindrome checker which my instructor says is more complex than it needs to be. I've read similar threads and googled around, but I'm completely stumped as to how to get it to work with fewer steps than this...

void isPal(string str){
int length = str.length();
if(length <= 1) cout << "Palindrome" << endl;//check for zero or one digit numbers
else if(str.at(0) == str.at(length -1)) {
    str = str.substr(1, (length - 2));
    isPal(str);}
else cout << "Not a palindrome." << endl;{
    cin >> str;}
like image 792
brock Avatar asked Dec 15 '22 02:12

brock


2 Answers

Check this:

int is_pal(int start, int end, string &str)
{
    if (start >= end)
        return 1;
    if (str[start] != str[end])
        return 0;
    return is_pal(++start, --end, str);   
}

Call the method from main. Let me know if that helps.. :)

like image 140
Rashad Avatar answered Dec 26 '22 11:12

Rashad


Use recursion

If you still want to use recursion, do something like:

bool isPal(const string &str, int start, int end)
{
    if (start >= end)   
        return true;
    if (str[start] != str[end])
        return false;
    return isPal(str, ++start, --end);   
}

And call isPal(str, 0, str.length()-1) in the main body. The idea is to use two indexes and move them as you don't want to use substr() every time in recursion.

Without recursion

Actually this problem is easy to do without using recursion as follows:

bool isPal(const string &str)
{
    int start=0, end=str.length()-1;
    while (start < end) {
        if (str[start++] != str[end--]) 
            return false;
    }
    return true;
}
like image 28
herohuyongtao Avatar answered Dec 26 '22 11:12

herohuyongtao