[PYTHON] LeetCode Solved: Valid Palindrome

Palindrome is a palindrome https://leetcode.com/problems/valid-palindrome/

Problem statement:

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.

Find out if the given sentence is a palindrome. However, ignore everything except alphanumeric characters (spaces, periods, symbols, etc.). Suppose an empty string is a palindrome. . . . . . .

This time we have to extract only alphanumeric characters. I thought it was okay because I couldn't use the regular expression library, but there is a method called isalnum. I did not know.... Answer 1: Try turning it obediently with a for sentence.

`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:
``````

Answer 2: Lambda style is neat. Reverse is also treated as a list and processed in one line for a clean look.

`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
``````

Recommended Posts