Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

4. A palindrome is a string that can be read backward and forward with the same

ID: 3669049 • Letter: 4

Question

4. A palindrome is a string that can be read backward and forward with the same result. For example, the following is a palindrome:

                        Able was I ere I saw Elba.

Write a function to test if a string is a palindrome using a stack. You can push characters in the stack one by one. When you reach the end of the string, you can pop the characters and form a new string. If the two strings are exactly the same, the string is a palindrome. Note that palindromes ignore spacing, punctuation, and capitalization. Test your program with the following test cases:

Go dog

Madam, I’m Adam

Madam, I’m not a palindrome

A man, a plan, a canal: Panama.

Explanation / Answer

#include <iostream>
#include <stack>
#include <string>

using namespace std;

void checkPalindrome(string input)
{
string orig = "";
string rev = "";
stack<char> mystack;
int i;

//removing spacing, punctuation, and capitalization

for (i=0; input[i]!=''; ++i)
{
    if(input[i]>='A'&&input[i]<='Z')
      orig = orig + (char)(input[i] + 32 );
    else if(input[i]>='a'&&input[i]<='z')
      orig = orig + input[i];
}
for (i=0; orig[i]!=''; ++i)
    mystack.push(orig[i]);

while (!mystack.empty())
{
     rev = rev + mystack.top();
     mystack.pop();
}

if(rev == orig)
    cout<<input<<" is Palindrome ";
else
    cout<<input<<" is not Palindrome ";
}
int main()
{
checkPalindrome("madam");
checkPalindrome("Able was I ere I saw Elba.");
checkPalindrome("Go dog");
checkPalindrome("Madam, I’m Adam");
checkPalindrome("Madam, I’m not a palindrome");
checkPalindrome("A man, a plan, a canal: Panama. ");

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote