isPalindrome
- Python
- JavaScript
def is_palindrome(s):
left, right = 0, len(s) - 1
while left < right:
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return True
// O(n) time
// O(1) space
/**
* @param {string} str
* @return {boolean}
*/
export default function isStringPalindrome(str) {
let leftIdx = 0;
const result = str
.replace(/[^a-zA-Z0-9]/g, '')
.toLowerCase();
let rightIdx = result.length - 1;
while (leftIdx < rightIdx) {
if (result[leftIdx] !== result[rightIdx]) {
return false;
}
leftIdx++;
rightIdx--;
}
return true;
}