前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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.
一开始做了一件特别逗的事情,就是从左往右统计了一下数字,然后再从右往左统计,如果一样则返回true,否则返回false。后来我发现我是不是傻,肯定这么做是做的。然后老老实实逐位置逐位置判断。 Your runtime beats 18.53% of java submissions.public class Solution {
public boolean isPalindrome(String s) {
s = s.toLowerCase();
boolean flag = true;
int i = 0,j=s.length()-1;
while( i < s.length() && j >=0){
if(isValid(s.charAt(i)) && isValid(s.charAt(j))){
if(s.charAt(i) != s.charAt(j)) {flag = false;break;}
else{ i ++; j --;}
}else{
if(!isValid(s.charAt(i))) i ++;
if(!isValid(s.charAt(j))) j --;
}
}
return flag;
}
public boolean isValid(char ch){
return Character.isDigit(ch) || Character.isAlphabetic(ch);
}
}