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;}
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.. :)
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With