# [LeetCode] Top Interview 150 Problems Solving # 125 Valid Palindrome

# **Understanding the Problem**

It is a palindrome problem with some extra steps to solve it. Some sentences are included in the test cases like `s = "A man, a plan, a canal: Panama"`. It is only to be left with lower case alpha numerical characters, which will form as `”amanaplanacanalpanama”` and this is a palindrome.

An empty string `s = ““` is also considered as a palindrome.

# **Approach**

It was nothing much to think personally, so I went with filtering the alpha numeric characters only. I wanted to go loop with `for` and check from both sides of the string.

# **Solution**

```python
class Solution:
    def isPalindrome(self, s: str) -> bool:
        new_s = ""
        for c in s:
            # if (c.lower() >= "a" and c.lower() <= "z") or (c.lower() >= "0" and c.lower() <= "9"):
            #     new_s += c.lower()
            if c.lower().isalnum():
                new_s += c.lower()

        if new_s == "":
            return True

        for i in range(len(new_s)//2):
            if new_s[i] != new_s[-(i+1)]:
                return False
        return True
```

Since I did not want to touch the `s`, I declared `new_s` to store alpha numeric characters. Here are steps I went through to solve the problem.

1. Check each character whether it is alpha numeric with `isalnum()` method. If `True`, add the character to `new_s` in lower case
    
2. Check if the string is empty
    
3. Check characters in `new_s` from the start and from the end at the same time. The checking will continue until it reaches the middle with `range(len(new_s)//2)`. If the length is odd, the rest after dividing the length of the sentence by 2 will be discarded, since it is unnecessary to consider the character right in the middle.
    
4. If the current position(left side) as `new_s[i]` and the other current position(right side) `new_s[-(i+1)]` are not equal, it means no palindrome thus return `False`, otherwise return `True`
    

# **Reflection**

Palindrome, to me, is always something that excites me, perhaps all problems related to string control do excite me.

I at first was solving the problem by checking alpha numeric characters in ascii value comparison like, `if (c.lower() >= "a" and c.lower() <= "z") or (c.lower() >= "0" and c.lower() <= "9"):`. I am not sure if it is common to compare and check the characters in this way, but I did it anyways. But then I found out that there is a method `isalnum()` as an internal python library and wrote this code down. I thought this would give me some time efficiency when using the method but it was nothing of a difference. It just makes the code look simpler.
