オットセイの経営日誌

データサイエンス系ベンチャーを経営してます。経営のこと、趣味のことつぶやきます。

LeetCode / Valid Palindrome

終日頭が重い@mhiro216です。
気象病ってやつなんだろうか。全部台風のせいだ。

www.d-yutaka.co.jp

さて、軽い問題で頭をほぐします。

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

問題を解くことよりも英語を正確に理解する方が難しいくらいかも?

英数字のみを抜き出し、大文字小文字の違いを無視して、回文(始めから読んでも、終わりから読んでも同じ)になっているかを判定する問題です。

解答・解説

解法1

私のsubmitしたコード。
正規表現を使い慣れている人なら、とりあえずreライブラリを使うこの解法は思いつくかと。

import re
class Solution:
    def isPalindrome(self, s: str) -> bool:
        new_s = re.sub(r'[^a-z0-9]', '', s.lower())
        return new_s == new_s[::-1]
解法2

私は初めて知りましたが、isalnumという、英数字かどうかを判定する関数(戻り値はbool型)があるんですね。これを使うと以下の通りです。

class Solution:
    def isPalindrome(self, s: str) -> bool:
        s = ''.join(e for e in s if e.isalnum()).lower()
        return s==s[::-1]

ちなみに文字列を同様に判定する関数には、以下3種類があるようです。ご参考まで。

  • isdecimal : 数字かどうか
  • isalpha  : 英字かどうか
  • isalnum  : 英数字かどうか