题目链接:https://leetcode.com/problems/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.
方法1:
class Solution{
public:
bool isPalindrome(string s)
{
string t="";
for(int i=0;i<s.length();i++)
{
if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')||(s[i]>='0'&&s[i]<='9'))
{
t.push_back((char)tolower(s[i]));
}
}
for(int i=0,j=(int)t.length()-1;i<j;i++,j--)
{
if(t[i]!=t[j])
return false;
}
return true;
}
};
方法2:
class Solution{
public:
bool isPalindrome(string s)
{
int begin=0,end=s.length()-1;
while(begin<end)
{
while(!((s[begin]>='a'&&s[begin]<='z')||(s[begin]>='A'&&s[begin]<='Z')||(s[begin]>='0'&&s[begin]<='9')))
begin++;
while(!((s[end]>='a'&&s[end]<='z')||(s[end]>='A'&&s[end]<='Z')||(s[end]>='0'&&s[end]<='9')))
end--;
if((begin<end)&&tolower(s[begin])!=tolower(s[end]))
return false;
begin++;
end--;
}
return true;
}
};