LeetCode之“字符串”:Valid Palindrome

时间:2021-04-23 07:14:46

  题目链接

  题目要求:

  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) {
if(!s.empty() && s.front() == ' ')
s.erase(, );
if(!s.empty() && s.back() == ' ')
s.pop_back(); bool ret = true;
int sz = s.size();
if(sz == )
return true; int i = ;
int j = sz - ;
while(i < j)
{
while(i < sz && !isalnum(s[i]))
i++;
while(j > - && !isalnum(s[j]))
j--;
if(i < sz && j > - && s[i] != s[j])
{
if(tolower(s[i]) != tolower(s[j]))
{
ret = false;
break;
}
}
i++;
j--;
} return ret;
}
};