LeetCode(125) Valid Palindrome

时间:2022-04-24 08:34:48

题目

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.

分析

判断给定字符串是否为忽略大小写,特殊符号,空格等之后的回文串。

AC代码

class Solution {
public:
bool isPalindrome(string s) {
if (s.empty())
return true; int size = s.length(); int lhs = 0, rhs = size - 1;
while (lhs < rhs)
{
if (!isalpha(s[lhs]))
{
++lhs;
continue;
}
if (!isalpha(s[rhs]))
{
--rhs;
continue;
}//if if (s[lhs] != s[rhs])
return false;
else
{
++lhs;
--rhs;
} }//while
return true;
}
//判断是否是字母数字,如果是大写字母则将其转化为小写字母
bool isalpha(char &c){
if ((c >= 'A'&&c <= 'Z')){
c = c - 'A' + 'a';
return true;
}
return (c >= 'a'&&c <= 'z') || (c >= '0'&&c <= '9');
}
};

GitHub测试程序源码