125. Valid Palindrome【双指针】

2017/3/15 21:47:04


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.

 

Subscribe to see which companies asked this question.


思路:判断回文串,利用双指针在两边向中间靠拢,依次判断两边指针指向的字符是否相等。
注意1.只能包含字母或数字;2.统一成大写或小写字母;
版本1 O(n)
public class Solution {
    public boolean isPalindrome(String s) {
		for ( int i=0,j=s.length()-1;i<j; )
        	if (Character.isLetterOrDigit(s.charAt(i)) && Character.isLetterOrDigit(s.charAt(j)) )
        		if (Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
        		else{
        			i++;j--;
        		}
        	else if (!Character.isLetterOrDigit(s.charAt(i))) i++;
        	else if (!Character.isLetterOrDigit(s.charAt(j))) j--;
        return true;
    }
}

  

耗时13ms,排名仅仅中间,toLowerCase函数比较耗时,需要多次调用函数,所以直接判断字符的差是否是32即可(‘0’和'P'也是差32~)。
 
版本2  耗时12ms,没多少区别。
public class Solution {
    public boolean isPalindrome(String s) {
		for ( int i=0,j=s.length()-1;i<j; )
        	if (Character.isLetterOrDigit(s.charAt(i)) && Character.isLetterOrDigit(s.charAt(j)) ){
        		if (s.charAt(i) == s.charAt(j) || (s.charAt(i)>64 && s.charAt(j)>64 && Math.abs(s.charAt(i) - s.charAt(j)) == 32) ){i++;j--;continue;};
        		return false;
        	}
        	else if (!Character.isLetterOrDigit(s.charAt(i))) i++;
        	else if (!Character.isLetterOrDigit(s.charAt(j))) j--;
        return true;
    }
}

  

 
版本3  (参考discuss) 利用正则表达式直接过滤非字母数字字符,简化代码。   41ms
public class Solution {
    public boolean isPalindrome(String s) {
        String actual = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
        return new StringBuffer(actual).reverse().toString().equals(actual);
    }
}

  

 
posted @ 2017-03-26 23:57  会飞的胖子  阅读(151)  评论(0编辑  收藏  举报