leetcode------Valid Palindrome

标题: Valid Palindrome
通过率: 21.9%
难度: 简单

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.

前面做过一次回文数的判断,回文数比这个题目难度大点,因为回文数不能用额外的空间,如果让用额外的空间就变成了本题,本题难点在于要去除标点符号,同时要忽略大小写,那么用java做就很简单了。用正则表达式把非数字字母全部置换成null就行了。然后就是从两头开始判断,只要是不相等就返回false,如果不用先有的函数,那么实现一个判断是否为字母数字的函数和一个大小写转换的函数即可,直接看代码:

 1 public class Solution {
 2     public boolean isPalindrome(String s) {
 3         int len=s.replaceAll("[^a-zA-Z0-9]","").length();
 4         String tmp=s.replaceAll("[^a-zA-Z0-9]","").toLowerCase();  
 5         if(len==0)return true;
 6         for(int i=0;i<len/2;i++){
 7             if(tmp.charAt(i)!=tmp.charAt(len-1-i)) return false;
 8         }
 9         return true;
10         
11     }
12 }

 

posted @ 2015-01-21 09:59  pku_smile  阅读(123)  评论(0编辑  收藏  举报