[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:

  • s consists only of printable ASCII characters.

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;
    }
}
上一篇:UOJ #455 [UER #8]雪灾与外卖 (贪心、模拟费用流)


下一篇:CodeForces - 932G Palindrome Partition