[Leet Code] Valid Palindrome

Matthew Boyd
1 min readJan 2, 2021

--

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

Problem:

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.

Solution:

class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s_arranged = list(re.sub('[\W_]+', '', s))
s_arranged = "".join(s_arranged)
result = list(re.sub('[\W_]+', '', s))
result.reverse()
result = "".join(result)
if s_arranged.lower() == result.lower():
return True
else:
return False

Explanation:

So the first part, we create a new variable that’s a list that has all the characters with all the whitespace removed. Then we join that together to create a string and reassign it back to the s_arranged variable. Then we create a new variable and we do the same procedure, the only difference is we reverse this one. Then we check if both the variables are the same, making sure to change them both to lowercase through the lower() method on the strings. If they’re the same, return True, and if they’re not the same return False.

--

--

Matthew Boyd
Matthew Boyd

Written by Matthew Boyd

Learning, and posting my findings!

No responses yet