Sponsored
Sponsored
This approach employs two pointers: one starting at the beginning of the string and the other at the end. The algorithm checks if the characters at these pointers are the same, ignoring case and non-alphanumeric characters. If they match, both pointers move inward. If they don't or if any pointer surpasses the other, the string is not a palindrome.
Time Complexity: O(n), where n is the length of the string, because we go through the string at most once.
Space Complexity: O(1), as we use a constant amount of space.
1class Solution:
2 def isPalindrome(self, s: str) -> bool:
3 left, right = 0, len(s) - 1
4 while left < right:
5 while left < right and not s[left].isalnum():
6 left += 1
7 while left < right and not s[right].isalnum():
8 right -= 1
9 if s[left].lower() != s[right].lower():
10 return False
11 left += 1
12 right -= 1
13 return True
14
15# Usage
16solution = Solution()
17print(solution.isPalindrome("A man, a plan, a canal: Panama"))This Python function checks if a given string is a palindrome by comparing characters from both directions. It skips non-alphanumeric characters and compares the rest while ignoring case, returning the correct result accordingly.
This approach first cleans the input string by removing non-alphanumeric characters and converting all letters to lowercase. It then compares the normalized string to its reverse to determine if it is a palindrome.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), because the cleaned string and its reverse require extra space proportional to n.
1const isPalindrome = function(s)
In JavaScript, this solution uses regular expressions to filter and clean the input and then leverage string manipulation techniques to check if cleaned string equals its reverse.