GoCalf Calf 的自留地 · 昙花一现

125. Valid Palindrome

Problem

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.

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

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 * 10⁵
  • s consists only of printable ASCII characters.

Test Cases

python
class Solution:
    def isPalindrome(self, s: str) -> bool:
solution_test.py下载完整源码
py
import pytest

from solution import Solution


@pytest.mark.parametrize('s, expected', [
    ("A man, a plan, a canal: Panama", True),
    ("race a car", False),
    (" ", True),
])
class Test:
    def test_solution(self, s, expected):
        sol = Solution()
        assert sol.isPalindrome(s) == expected

Thoughts

从两头向中间扫描,跳过非字母数字。

Code

py
class Solution:
    def isPalindrome(self, s: str) -> bool:
        i = 0
        j = len(s) - 1
        while i < j:
            if not s[i].isalnum():
                i += 1
            elif not s[j].isalnum():
                j -= 1
            elif s[i].lower() != s[j].lower():
                return False
            else:
                i += 1
                j -= 1

        return True

评论需要 JavaScript。