[leetcode]Valid Palindrome

事实证明,是时间而不是tolowcase的问题。新博文地址:[leetcode]Valid Palindrome

Valid Palindrome

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.

 alphanumeric坑爹啊,我还以为是字母,居然是坑爹的字母数字,第一次超时,用了toLowerCase,估计这个方法比较坑,最后还是老老实实手动判断大小写。

  public boolean isPalindrome(String s) {
    	if(s == null || s.length() == 0){
    		return true;
    	}
    	StringBuilder sb = new StringBuilder();
    	for(int i = s.length() - 1 ;i >= 0; i--){//这里可以优化,无需过滤,遇到非法字符跳过
    		if((s.charAt(i) >= '0' && s.charAt(i) <= '9')||(s.charAt(i) >= 'a'  && s.charAt(i) <= 'z' )|| (s.charAt(i) >= 'A'  && s.charAt(i) <= 'Z' )){
    			sb.append(s.charAt(i));
    		}	
    	}
    	s = sb.toString();
    	for(int i = 0 ; i < s.length() / 2; i++){
    		if(s.charAt(i) != s.charAt(s.length() - 1 - i) && s.charAt(i) != s.charAt(s.length() - 1 - i) + 32 && s.charAt(i) != s.charAt(s.length() - 1 - i) - 32){
    			return false;
    		}
    	}
    	return true;
    }

 

 

你可能感兴趣的:(LeetCode)