Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
直接贴上本娃子的代码:
class Solution {
public boolean isPalindrome(String s) {
String s1 = s.replaceAll("[^0-9a-zA-Z]","");
s1 = s1.toLowerCase();
char[] b = s1.toCharArray();
int min = 0;
int max = b.length-1;
while(min<max){
if(b[min] != b[max]){
return false;
}
else{
min++;
max--;
}
}
return true;
}
}
做这道题的时候有两个点:
1.取length一直报错“cannot find symbol: variable length”,然后网上查了一下:
length()是求String字符串对象中字符的个数,而length是求字符串数组中有多少个字符串,size()方法是求泛型集合有多少个元素。
2.要注意大小写,a不等于A的,所以可以先将大小写字母统一,这个是我调试的时候发现的。
不过我这个运行时间是27ms,应该是我用了replaceAll的缘故。看了一下文档的方法,代码如下:
class Solution {
public boolean isPalindrome(String s) {
int i=0, j=s.length()-1;
while(i<j){
while(i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
while(i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
if(Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) {
return false;
}
i++;
j--;
}
return true;
}
}
该代码运行用了5ms,节省了22ms!还是这么小一个程序。好厉害。