A palindrome is a string that reads the same forwards or backwards; for example
ID: 3660186 • Letter: A
Question
A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string). Write a recursive, bool-valued function, isPalindrome that accepts a string and returns whether the string is a palindrome. A string, s, is a palindrome if: s is the empty string or s consists of a single letter (which reads the same back or forward), or the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters) form a palindrome. my code is bool isPalindrome(string str){ if(str.length()==1||str.length()==0)return true; else if(str.substr(0)!=str.substr(str.length()-1)) return false; else return isPalindrome(str.substr(1, str.length()-2)); }Explanation / Answer
I used s instead of str but hopefully you'll figure it out and understand what is different from yours and mine
bool isPalindrome(string s){
//if it is empty return true
if (s == "")
return true;
// returns false if first and last is not the same
else if (s[0] != s[s.length()-1])
return false;
//recursively cycles by creating substring deleting first and last character
return isPalindrome(s.substr(1,s.length()-2));
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.