|
| 1 | +Original: https://leetcode.com/problems/valid-palindrome/solutions/5056369/simple-2-line-python3-solution-beats-91-on/ |
| 2 | + |
| 3 | +# Intuition |
| 4 | +We simply remove the unwanted characters from the string, convert to lowercase, and reverse the string and then compare to the original. |
| 5 | + |
| 6 | +# Approach |
| 7 | +- Import the Python Regex module |
| 8 | +- Convert input string to lowercase |
| 9 | +- Use it remove the unwanted characters, which are all characters excluding letters and numbers |
| 10 | +- Now that we have the *cleaned* input string, compare it to the reversed version of itself, and return the result. |
| 11 | + |
| 12 | +# Complexity |
| 13 | +- Time complexity: |
| 14 | + $$O(n)$$ |
| 15 | + Note: This excludes the time taken by the Python Regex module(`re`) to match and substitute the unwanted characters from the input string. |
| 16 | + This [StackOverflow answer](https://stackoverflow.com/a/21702/2627137) says its $$O(2^m + n)$$, where m is length of regex string, and n is length of input string |
| 17 | + |
| 18 | + Reversing the string is an O(n) operation. And so is string comparison. |
| 19 | + Therefore overall complexity exhibits linear growth along with size of input. |
| 20 | + |
| 21 | +- Space complexity: |
| 22 | + $$O(n)$$ |
| 23 | + |
| 24 | +# Code |
| 25 | +```python |
| 26 | +import re |
| 27 | + |
| 28 | +class Solution: |
| 29 | + def isPalindrome(self, s: str) -> bool: |
| 30 | + s_clean = re.sub('[^a-z0-9]','',s.lower()) |
| 31 | + return s_clean==s_clean[::-1] |
| 32 | +``` |
0 commit comments