## Problem https://leetcode.com/problems/valid-palindrome/ <br> :::spoiler **Optimal Space & Time Complexity** ``` ``` ::: <br> <hr/> ## Solutions :::spoiler 東 ```javascript= ``` ::: <br> :::spoiler Hao ```javascript= // Time complexity: O(n) where n === s.length // Space complexity: O(1) const codes = { '0': 48, '9': 57, 'A': 65, 'Z': 90, 'a': 97, 'z': 122, }; const upperLowerCodeDiff = codes['A'] - codes['a']; const isNumber = (code) => code >= codes['0'] && code <= codes['9']; const isUpperAlphabet = (code) => code >= codes['A'] && code <= codes['Z']; const isLowerAlphabet = (code) => code >= codes['a'] && code <= codes['z']; const isAlphanumeric = (code) => isNumber(code) || isUpperAlphabet(code) || isLowerAlphabet(code); const isEqualAlphanumeric = (codeLeft, codeRight) => { if (isNumber(codeLeft) && isNumber(codeRight)) return codeLeft === codeRight; else if (!isNumber(codeLeft) && !isNumber(codeRight)) { const lowerCodeLeft = isUpperAlphabet(codeLeft) ? codeLeft - upperLowerCodeDiff : codeLeft; const lowerCodeRight = isUpperAlphabet(codeRight) ? codeRight - upperLowerCodeDiff : codeRight; return lowerCodeLeft === lowerCodeRight; } else return false }; var isPalindrome = function(s) { let res = s.length > 0; let left = 0; let right = s.length - 1; while (res && left <= right) { const codeLeft = s.charCodeAt(left); const codeRight = s.charCodeAt(right); if (!isAlphanumeric(codeLeft)) { left += 1; continue; } if (!isAlphanumeric(codeRight)) { right -= 1; continue; } res = isEqualAlphanumeric(codeLeft, codeRight); left += 1; right -= 1; } return res; }; ``` ::: <br> :::spoiler YC ```javascript= ``` ::: <br> :::spoiler SOL ```javascript= ``` ::: --- ## Supplement / Discussion ### 東 ### Hao - string ⇒ array ⇒ 線性結構 ⇒ palindrome ⇒ two pointer ⇒ 左右指針 - converting all uppercase letters into lowercase letters - uppercase = lowercase - removing all non-alphanumeric characters, characters other than letters and numbers - How to differentiate? `String.prototype.charCodeAt()` | chars | codes | | --- | --- | | 0-9 | 48-57 | | A-Z | 65-90 | | a-z | 97-122 | - Could replace self-implemented func `isEqualAlphanumeric()` with native `string.prototype.toLowerCase()` ### YC ### SOL