leetcode Algorithmic Question 125 (Simple 033) Roman Number to Integer
- Topic introduction
Given a string, verify that it is a palindrome string, only letters and numeric characters are considered, and the case of letters can be ignored. Note: In this topic, we define empty strings as valid palindrome strings.
- Example
Input: "A man, a plan, a canal: Panama" output: true
Input: "race a car" output: false
- Solution one
/** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { let start = 0, end = s.length - 1; while (start < end) { while(start < end && isSymbol(s.charCodeAt(start))) { start++; } while(start < end && isSymbol(s.charCodeAt(end))) { end--; } if(start >= end) { return true; } if(!isEqual(s.charCodeAt(start), s.charCodeAt(end))) { return false; } start++; end--; } return true; }; const isSymbol = ascii => { return ascii < 48 || ascii > 122 || (ascii > 57 && ascii < 65) || (ascii > 90 && ascii < 97); } const isEqual = (ascii1, ascii2) => { if(ascii1 === ascii2) { return true; } if(ascii1 <=57 || ascii2 <= 57) { return false; } return Math.abs(ascii1 - ascii2) === 32; }
Execution time: 396 ms, beating 5.05% of all JavaScript submissions
Memory consumption: 58.1 MB, beating 5.08% of all JavaScript submissions
- Solution two
/** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { let start = 0, end = s.length - 1; s = s.toLocaleLowerCase(); while (start < end) { while(start < end && isSymbol(s.charAt(start))) { start++; } while(start < end && isSymbol(s.charAt(end))) { end--; } if(start >= end) { return true; } if(s.charAt(start) !== s.charAt(end)) { return false; } start++; end--; } return true; }; const isSymbol = c => { return '0123456789abcdefghijklmnopqrstuvwxyz'.indexOf(c) === -1; }
Execution time: 100 ms, beating 80.14% of all JavaScript submissions
Memory consumption: 25.5 MB, beating 98.30% of all JavaScript submissions
- Solution three
/** * @param {string} s * @return {boolean} */ var isPalindrome = function(s) { s = s.replace(/[^a-zA-Z0-9]/g, '').toLocaleLowerCase(); return s === s.split('').reverse().join(''); // return s.replace(/[^a-zA-Z0-9]/g, '').toLocaleLowerCase() === s.replace(/[^a-zA-Z0-9]/g, '').toLocaleLowerCase().split('').reverse().join(''); };
Execution time: 100 ms, beating 80.14% of all JavaScript submissions
Memory consumption: 38.1 MB, beating 49.06% of all JavaScript submissions