Tech for good

[Neetcode/String Preprocessing ] Valid Palindrome 본문

IT/Computer Science

[Neetcode/String Preprocessing ] Valid Palindrome

Diana Kang 2025. 6. 24. 11:42

https://neetcode.io/problems/is-palindrome?list=neetcode150

 

NeetCode

 

neetcode.io

 

 

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

ss = ''

  • Initialize an empty string to store the cleaned version of s.

if c.isalnum():

  • isalnum() checks if the character is alphanumeric (letter or number).
  • This filters out spaces, punctuation, symbols, etc.

ss += c.lower()

  • Convert the character to lowercase and append it to the cleaned string.
  • This makes the check case-insensitive.

return ss == ss[::-1]

  • ss[::-1] reverses the cleaned string.
  • If the cleaned string is the same as its reverse, it's a palindrome → return True.

✅ Example Test:

s = "Was it a car or a cat I saw?"
ss = "wasitacaroracatisaw"
ss[::-1] = "wasitacaroracatisaw"
→ returns True

 

📌 Summary:

You implemented the correct logic using:

  • isalnum() for filtering
  • lower() for case insensitivity
  • [::-1] for palindrome check