I'm creating a simple function to verify whether or not a string is a palindrome, and must use stacks in solving it.
bool isPalindrome(string word) {
// #1 determine length
int n = word.size();
// #3 make sure we have an even string
if (n % 2 != 0)
word.erase(0, 1);
// #2 load the stack
stack<char> s;
for (int i = 0; i < n / 2; i++) {
s.push(word[i]);
word.erase(i, 1);
}
// #4 if our stack is empty, then return true
if (s.empty())
return true;
// #5 compare the first & last letters for a valid palindrome
/*if (s.top() == word[0]) {
s.pop();
word.erase(0, 1);
} else
return false;*/
while (n != 0) {
if (s.top() == word[0]) {
s.pop();
word.erase(0, 1);
// return true only when our stack is empty
if (s.empty())
return true;
} else
return false;
}
}
Is there a better way to do this? Are there any evident issues with the current state of the program?