其他分享
首页 > 其他分享> > [String][3]Leetcode125. Valid Palindrome

[String][3]Leetcode125. Valid Palindrome

作者:互联网

125. Valid Palindrome

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

Constraints:

Solution1: Two Pointers

class Solution {
    public boolean isPalindrome(String s) {
        //Character class 
        //Character.toLowerCase(); 全部变成小写
        //Character.isLetterOrDigit(); 判断是否有特殊字符和数字
        
        //Solution: Two Pointers,一个指向头,一个指向尾,两个指针向中间移动;
        if(s.length() == 0 || s==null ) return true;
        
        for(int i = 0, j = s.length() -1; i <j; ++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;
        }
        
        return true;
    }
}

标签:Palindrome,return,String,Character,Valid,toLowerCase,true,isLetterOrDigit,charAt
来源: https://blog.csdn.net/chenxinjk2/article/details/113448549