125. Valid Palindrome(E)

https://leetcode.com/problems/valid-palindrome/

A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.

Given a string s, return true if it is a palindrome, or false otherwise.

Example 1:

Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.

Example 2:

Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.

Example 3:

Input: s = " "
Output: true
Explanation: s is an empty string "" after removing non-alphanumeric characters.
Since an empty string reads the same forward and backward, it is a palindrome.

Constraints:

  • 1 <= s.length <= 2 * 105

  • s consists only of printable ASCII characters.

Solution:

https://www.jiuzhang.com/problem/valid-palindrome/ 使用两根指针遍历整个字符串即可.

假定有指针i, j, 其中i是从前往后遍历, j是从后往前遍历.

当i在j左边时继续循环, 每一次将i右移到数字/字母上, j左移到数字/字母上,

比较二者对应的字符串内的字符是否相同, 不相同则原字符串不是回文串.

如果全部的比较都相同, 说明是回文串.

lass Solution {
    public boolean isPalindrome(String s) {
        if (s == null || s.length() == 0) {
            return true;
        }
        
        s = s.toLowerCase();
        int i = 0; 
        int j = s.length()-1;
        while(i<j)
        {
            while(i < s.length() && !isValid(s.charAt(i)))
            {i++;}
            while(j >= 0 && !isValid(s.charAt(j)))
            {j--;}
            if(i< j && s.charAt(i) != s.charAt(j))
            {
                return false;
            }
            i++;
            j--;
        }
        return true;
        
        
    }
    
    public boolean isValid(char c)
    {
        return Character.isLetter(c) || Character.isDigit(c);
    }
}

Last updated