0
0

More than 3 years have passed since last update.

LeetCode解いた: Valid Palindrome

Posted at

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

Constraints:
s consists only of printable ASCII characters.

与えられた文が回文になるか調べます。ただし英数字以外はすべて無視します(スペース、ピリオド、記号その他諸々)。空のストリングは回文であるとします。
.
.
.
.
.
.

今回は英数字のみを抽出しなければなりません。
正規表現のライブラリ使えないのでまいったなと思ったけど、isalnumというメソッドがあるのですね。知らなかった...。
解答1:素直にfor文で回してみる。

solution.py
class Solution:
    def isPalindrome(self, s: str) -> bool:

        alphanumeric_filter = filter(str.isalnum, s)
        alphanumeric_string = "".join(alphanumeric_filter).lower()

        reverse_text = ""
        for i in range(1,len(alphanumeric_string)+1):
             reverse_text += alphanumeric_string[len(alphanumeric_string)-i]

        return alphanumeric_string == reverse_text:

解答2:ラムダ式ですっきり。reverseもリスト扱いで一行で処理してすっきり。

solution.py
class Solution:
    def isPalindrome(self, s: str) -> bool:

        filtered = filter(lambda ch: ch.isalnum(), s)
        lowercase = map(lambda ch: ch.lower(), filtered)

        processed_list = list(lowercase)
        reversed_list = processed_list[::-1]

        return processed_list == reversed_list
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0