Decided to try and cook up a solution. Did some testing, it handled all the test cases I threw at it correctly. It's not exactly a pretty solution, but eh.
#include <list>
inline bool isAlphanumeric(_TCHAR ch) {
return ((ch >= 'a') && (ch <= 'z') || (ch >= 'A') && (ch <= 'Z') || (ch >= '0') && (ch <= '9'));
}
int isPalindrome(_TCHAR* string) {
// init
if (string == 0) return -1;
_TCHAR *c = string;
std::list<_TCHAR> stack;
// build stack
while (*c != 0)
stack.push_back(*c++);
_TCHAR a, b;
while (stack.size() > 1) {
// pull the start and end items off the stack
a = stack.front(); b = stack.back();
stack.pop_front(); stack.pop_back();
if (a != b) return 0;
// they are both equal so just test one
if (!isAlphanumeric(a)) return 0;
}
// if the middle character is not alphanumeric the stack scanning algorithm won't catch it, so check
if ((stack.size() > 0) && (!isAlphanumeric(stack.back()))) return 0;
return 1;
}
Gary Daniels and Evan Goldring - Mock whiteboard problem
Aug 26, 2004 at 1:50 PM