题目要求:
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.
解决思路:首先要将字符串统一为大写(小写),我这统一为小写。然后要剔除字符串中的非字母和数字。Character类中有一个静态方法isLetterOrDigit(),可以实现。处理完后就可以再数组中来判断是否是回文了。
代码实现:
<span style="font-size:14px;">public class ValidPalindrome {
public boolean isPalindrome(String s) {
char []c=s.toLowerCase().toCharArray();//将大小写统一为小写,然后转换为字符数组
char []b=new char[c.length];//用来存储字符串中的数字和字母
boolean flag=true;
int count=0;//统计b的长度
for(int i=0;i<c.length;i++){//剔除非字母和数字
if(Character.isLetterOrDigit(c[i]))
b[count++]=c[i];
}
for(int i=0;i<count/2;i++){//判断是否是回文
if(b[i]==b[count-1-i]) flag=true;
else{
flag=false;
break;
}
}
return flag;
}</span>
感觉我的时间控制的不是很好。