125.Valid-Palindrome

125. Valid Palindrome

题目地址

https://leetcode.com/problems/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

代码

public class Solution {
    public boolean isPalindrome(String s) {
    // 1. input validation
    if (s == null || s.trim().isEmpty()) return  true;

    // 2. Filter punctuation character 
    int l = 0;
    int r = s.length() - 1;
    while (l < r) {
      // 先过滤
      if (!Character.isLetterOrDigit(s.charAt(l))) {
        l++;
        continue;
      }
      if (!Character.isLetterOrDigit(s.charAt(r))) {
        r--;
        continue;
      }


      // 判断 left 和 right
      if (Character.toLowerCase(s.charAt(l)) == Character.toLowerCase(s.charAt(r))) {
        l++;
        r--;
      } else {
        return false;
      }

    }

      return true;
  }
}

Last updated