125. Valid Palindrome [Easy]
125. 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.
Constraints:
- 1 <= s.length <= 2 * 105
 - s consists only of printable ASCII characters.
 
Example
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
思路
经典双指针回文字符串,两个关键点
- 大写转成小写
 - 移除字母数字外的其他字符,且是在ASCII字符集中的
 
那只要针对这两点拿到符合要求的回文串,接下来就是无脑的左右指针中间靠了
题解
- 无脑快速AC
 
    public boolean isPalindrome(String s) {
        int left, right;
	// 先全部转成小写
        char[] data = s.toLowerCase().toCharArray();
        left = 0;
        right = data.length - 1;
        while (left < right) {
	    // 首先左指针要小于右指针,然后就看当前是否是小写字母或数字,不是就跳过
            while (left < right && !isAlphaOrNum(data[left]))
                left++;
            while (left < right && !isAlphaOrNum(data[right]))
                right--;
            if (data[left] != data[right])
                return false;
            left++;
            right--;
        }
        return true;
    }
    public boolean isAlphaOrNum(char c) {
        return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z');
    }

                
            
        
浙公网安备 33010602011771号