|
| 1 | + |
| 2 | +import re |
| 3 | + |
| 4 | +class Solution: |
1 | 5 | # Palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring non-alphanumeric characters - letters and number). |
2 | 6 | # the solution should first filter out non-alphanumeric characters and convert the string to lowercase. |
3 | 7 | # Then, it should check if the cleaned string is equal to its reverse. |
4 | 8 |
|
5 | 9 | # Time complexity = O(n), as it checks, replaces, converts to lowercase, and reverses all characters in the string |
6 | 10 | # Space complexity = O(n), as it creates a new string with a maximum length equal to the original string |
7 | | -import re |
8 | | - |
9 | | -class Solution: |
10 | 11 | def isPalindrome(self, s: str) -> bool: |
11 | 12 | filtered_string = re.sub(r'[^a-zA-Z0-9]','',s).lower() |
12 | 13 | reversed_string = filtered_string[::-1] |
13 | 14 | return reversed_string == filtered_string |
| 15 | + |
| 16 | + |
| 17 | +# Using Two-pointer; It searches from given string directly so the Space complexity is O(n) - better method |
| 18 | +# By using two index, searchs and compares from start and end of the string like this -><- |
| 19 | +# Do this while start index is less than end index |
| 20 | +# Skip non-alphanumeric characters |
| 21 | +# If both pointer are in characters, then convert to lowercase and compare |
| 22 | +# If not equal, return false |
| 23 | +# If all characters are equal, return true |
| 24 | + |
| 25 | +# Time complexity = O(n), as it checks and converts to lowercase all characters in the string |
| 26 | +# Space complexity = O(1), as it uses only a constant amount of extra space |
| 27 | + def isPalindromeTwoPointer(self, s: str) -> bool: |
| 28 | + left = 0 |
| 29 | + right = len(s) - 1 |
| 30 | + |
| 31 | + while left < right: |
| 32 | + if not s[left].isalnum(): |
| 33 | + left+=1 |
| 34 | + continue |
| 35 | + if not s[right].isalnum(): |
| 36 | + right-=1 |
| 37 | + continue |
| 38 | + if s[left].lower() != s[right].lower(): |
| 39 | + return False |
| 40 | + |
| 41 | + left+=1 |
| 42 | + right-=1 |
| 43 | + |
| 44 | + return True |
0 commit comments