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.
这道题考查的是指定字符的回文数字的判断。
建议和leetcode 680. Valid Palindrome II 去除一个字符的回文字符串判断 + 双指针 一起学习
代码如下:
public class Solution
{
//判断是否是回文数:这个题只考虑小写字符和数字,别的是不考虑的
public boolean isPalindrome(String s)
{
if(s==null || s.length()<=1)
return true;
s=s.replace(" ", "");
s=s.toLowerCase();
int i=0,j=s.length()-1;
while(i<j)
{
if(isVaild(s.charAt(i))==false)
{
i++;
continue;
}else if(isVaild(s.charAt(j))==false)
{
j--;
continue;
}else if(s.charAt(i)!=s.charAt(j))
return false;
else
{
i++;
j--;
}
}
return true;
}
//判断是否是我们要检查的字符
boolean isVaild(char c)
{
if(c>='a' && c<='z' || c>='0' && c<='9')
return true;
else
return false;
}
}
下面是C++的做法,就是做一个遍历,这道题最大的收获就是学会使用transform函数
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution
{
public:
bool isPalindrome(string s)
{
string a = s;
transform(s.begin(),s.end(),a.begin(),::tolower);
int i = 0, j = a.length() - 1;
while (i < j)
{
if (isVaild(a[i]) && isVaild(a[j]))
{
if (a[i] != a[j])
return false;
else
{
i++;
j--;
}
}
else if(isVaild(a[i]) && !isVaild(a[j]))
j--;
else if (!isVaild(a[i]) && isVaild(a[j]))
i++;
else
{
i++;
j--;
}
}
return true;
}
bool isVaild(char a)
{
if (a >= '0' && a <= '9' || a >= 'a' && a <= 'z')
return true;
else
return false;
}
};