首页 > 其他分享 >125. Valid Palindrome [Easy]

125. Valid Palindrome [Easy]

时间:2023-01-10 17:12:47浏览次数:48  
标签:Palindrome return Valid right 125 && 指针 data left

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');
    }

标签:Palindrome,return,Valid,right,125,&&,指针,data,left
From: https://www.cnblogs.com/tanhaoo/p/17040501.html

相关文章