有效回文串

给定一个字符串,判断其是否为一个回文串。只包含字母和数字,忽略大小写。

样例

"A man, a plan, a canal: Panama" 是一个回文。

"race a car" 不是一个回文。

注意

你是否考虑过,字符串有可能是空字符串?这是面试过程中,面试官常常会问的问题。

在这个题目中,我们将空字符串判定为有效回文。

挑战

O(n) 时间复杂度,且不占用额外空间。

public class Solution {
    /**
     * @param s A string
     * @return Whether the string is a valid palindrome
     */
    public boolean isvalid(char c){
        return Character.isLetter(c)||Character.isDigit(c);
    }
    public boolean isPalindrome(String s) {
        // Write your code here
        if(s == null)   return true;
        if(s.length() == 0)  return true;
        int start = 0;
        int end = s.length()-1;
        while(start < end){
            while(start < s.length() && !isvalid(s.charAt(start))){
                start++;
            }
            if(start == s.length())  return true;
            while(end >= 0 && !isvalid(s.charAt(end))){
                end--;
            }
            if(Character.toLowerCase(s.charAt(start)) != Character.toLowerCase(s.charAt(end))) {
                break;
            } else {
                start++;
                end--;
            }
        }
        return end<=start;
    }
}

  

原文地址:https://www.cnblogs.com/wangnanabuaa/p/5126055.html