LeetCode Top Interview Questions 125. Valid Palindrome (Java版; Easy)

welcome to my blog

LeetCode Top Interview Questions 125. Valid Palindrome (Java版; Easy)

题目描述

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Note: For the purpose of this problem, we define empty string as valid palindrome.

Example 1:

Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:

Input: "race a car"
Output: false

第一次做; 双指针法; 简洁版; 核心:在内循环中继续使用left
class Solution {
    public boolean isPalindrome(String s) {
        if(s.isEmpty())
            return true;
        //
        s = s.toLowerCase();
        int left=0, right=s.length()-1;
        while(left<right){
            while(left<right && !Character.isLetterOrDigit(s.charAt(left))){
                left++;
            }
            while(left<right && !Character.isLetterOrDigit(s.charAt(right))){
                right--;
            }
            //here, left==right或者s.charAt(i)是letterOrDigit
            //下面这个if中可以不用加left
            if(left<right && s.charAt(left)!=s.charAt(right)){
                return false;
            }
            //update
            left++;
            right--;
        }
        return true;
    }
}

第一次做; 很容易想到双指针做法; 但是要注意特殊情况的处理:比如输入为空, 输入全是特殊字符, 这两种情况都要返回true; 处理逻辑不够简洁

class Solution {
    public boolean isPalindrome(String s) {
        if(s==null || s.length()==0)
            return true;
        int n=s.length();
        s = s.toLowerCase();
        int left=0, right=s.length()-1;
        char ch1 = s.charAt(left), ch2 = s.charAt(right);
        boolean res = true;
        while(left<right){
            while(!valid(ch1) && left+1<n){
                ch1=s.charAt(++left);
            }
            while(!valid(ch2) && right-1>=0){
                ch2=s.charAt(--right);
            }
            if(!valid(ch1) && !valid(ch2)){
                continue;
            }
            if(ch1!=ch2){
                res = false;
                break;
            }
            //update
            if(left==n-1 || right==0)
                break;
            ch1 = s.charAt(++left);
            ch2 = s.charAt(--right);
        }
        return res;
    }
    public boolean valid(char ch){
        return (ch>='0'&&ch<='9')||(ch>='a'&&ch<='z');
    }
}

力扣优秀题解; 巧妙地地方:在两个内循环中接着使用了i
class Solution {
    public boolean isPalindrome(String s) {
        int i = 0, j = s.length() - 1;
        while(i < j){
            while(i < j && !Character.isLetterOrDigit(s.charAt(i))) i++;
            while(i < j && !Character.isLetterOrDigit(s.charAt(j))) j--;
            if(Character.toLowerCase(s.charAt(i)) != Character.toLowerCase(s.charAt(j))) return false;
            i++; j--;
        }
        return true;
    }
}

你可能感兴趣的:(LeetCode,Top,Interview,Questions,LeetCode)