• 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);
        }
    }
    

      

     
  • 相关阅读:
    [APIO2012]派遣
    Luogu_2774 方格取数问题
    Luogu4149 [IOI2011]Race
    Luogu_4886 快递员
    Loj_6282. 数列分块入门 6
    LOJ 6281 数列分块入门 5
    三维偏序 cdq
    【逆序对】 模板
    【luogu P1637 三元上升子序列】 题解
    【luogu P3609 [USACO17JAN]Hoof, Paper, Scissor蹄子剪刀布】 题解
  • 原文地址:https://www.cnblogs.com/flyfatty/p/6624794.html
Copyright © 2020-2023  润新知