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.
题目大意:判断字符串是否为回文串,只考虑字母和数字字符,并且不考虑大小写,因此判断时可跳过标点符号和空格等,或者去除非字母和数字字符等,我这里采用的是第二种方法,复杂度会相对高一些。
public class Solution {
public boolean isPalindrome(String s) {
if(s==null)
return true;
int length=s.length();
s=s.toLowerCase();
StringBuilder temps=new StringBuilder();
for(int i=0;i<length;i++)
{
if((s.charAt(i)>='a'&&s.charAt(i)<='z')||(s.charAt(i) >= '0' && s.charAt(i) <= '9'))
{
String temp=String.valueOf(s.charAt(i));
temps.append(temp);
}
}
s=temps.toString();
length=s.length();
for(int i=0;i<length/2;i++)
{
if(s.charAt(i)!=s.charAt(length-1-i))
return false;
}
return true;
}
}