Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
class Solution
{
public:
bool isPalindrome(string s)
{
int nBegin = 0, nEnd = s.length() - 1;//分别在头和尾做两个标记
while (nBegin < nEnd)//如果头标记在尾标记的前面则继续循环
{
if ((s[nBegin] >= '0'&&s[nBegin] <= '9') || (s[nBegin] >= 'A'&&s[nBegin] <= 'Z'))
{
}
else if (s[nBegin] >= 'a'&&s[nBegin] <= 'z')//如果头标记的符号是小写字母则转换为大写
{
s[nBegin] = s[nBegin] - 32;
}
else//如果头标记的符号不是符号数字类型,则将头标记加1
{
nBegin++;
continue;
}
if ((s[nEnd] >= '0'&&s[nEnd] <= '9') || (s[nEnd] >= 'A'&&s[nEnd] <= 'Z'))
{
}
else if (s[nEnd] >= 'a'&&s[nEnd] <= 'z')//如果尾标记的符号是小写字母则转换为大写
{
s[nEnd] = s[nEnd] - 32;
}
else//如果尾标记的符号不是符号数字类型,则将尾标记减1
{
nEnd--;
continue;
}
if (s[nBegin] != s[nEnd])//如果当前头标记和尾标记的符号不相同则返回false
{
return false;
}
else//如果当前头标记和尾标记的符号相同则将头标记加1,尾标记减1
{
nBegin++;
nEnd--;
}
}
return true;
}
};
由于编程和算法能力有限,有些答案可能不够鲁棒和高效,希望有好方法的人能多多指教,帮助楼主提高水平,谢谢。