leetcode 125

时间:2022-02-20 23:52:14

125. Valid Palindrome

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 n = s.size();
int st = ;
if(n == )
{
return true;
}
n--;
while(st < n)
{
if(isValid(s[st]) && isValid(s[n]))
{
if(s[st] <= && s[st] >= )
{
if(s[n] > || s[n] < )
{ return false;
}
else if(s[st] != s[n])
{
return false;
}
else
{
st++;
n--;
continue;
}
}
if(s[st] == s[n] || s[st]-s[n] == || s[n]-s[st] == )
{
st++;
n--;
continue;
}
else
{
return false;
}
}
else if(isValid(s[st]))
{
n--;
}
else if(isValid(s[n]))
{
st++;
}
else
{
n--;
st++;
}
}
return true;
}
bool isValid(char s)
{
if(s < || s > )
{
return false;
}
else if(s > && s < )
{
return false;
}
else if(s > && s < )
{
return false;
}
return true;
}
};