Skip to content

Commit bc0870a

Browse files
authored
Merge pull request neetcode-gh#1411 from brentonjackson/patch-1
Update 125-Valid-Palindrome.js
2 parents 2254ccc + 767ebf8 commit bc0870a

File tree

1 file changed

+21
-41
lines changed

1 file changed

+21
-41
lines changed

javascript/125-Valid-Palindrome.js

Lines changed: 21 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -31,47 +31,27 @@ const reverse = (s) => s
3131
* @return {boolean}
3232
*/
3333
var isPalindrome = function(s) {
34-
if (!s.length) return true;
35-
36-
return isValid(s);/* Time O(N) */
37-
};
38-
39-
const isValid = (s) => {
40-
let [ left, right ] = [ 0, (s.length - 1) ];
41-
42-
while (left < right) { /* Time O(N) */
43-
[ left, right ] = moveToMid(s, left, right);/* Time O(N) */
44-
45-
const [ leftCode, rightCode ] = getCodes(s, left, right);
46-
47-
const isEqual = leftCode === rightCode;
48-
if (!isEqual) return false;
49-
50-
left++; right--;
34+
if (s.length <= 1) return true;
35+
36+
let [left, right] = [0, s.length - 1];
37+
let leftChar, rightChar;
38+
while (left < right) {
39+
leftChar = s[left];
40+
rightChar = s[right];
41+
42+
// skip char if non-alphanumeric
43+
if (!/[a-zA-Z0-9]/.test(leftChar)) {
44+
left++;
45+
} else if (!/[a-zA-Z0-9]/.test(rightChar)) {
46+
right--;
47+
} else {
48+
// compare letters
49+
if (leftChar.toLowerCase() != rightChar.toLowerCase()) {
50+
return false;
51+
}
52+
left++;
53+
right--;
54+
}
5155
}
52-
5356
return true;
54-
}
55-
56-
const moveToMid = (s, left, right) => {
57-
while ((left < right) && !isAlphaNumeric(s[left])) left++; /* Time O(N) */
58-
while ((left < right) && !isAlphaNumeric(s[right])) right--;/* Time O(N) */
59-
60-
return [ left, right ];
61-
}
62-
63-
const getCodes = (s, left, right) => [ getCode(s[left]), getCode(s[right]) ];
64-
65-
const getCode = (char) => char.toLowerCase().charCodeAt(0);
66-
67-
const isAlphaNumeric = (char) => {
68-
const code = getCode(char);
69-
70-
const [ a, z ] = [ 97, 122 ];
71-
const isAlpha = (a <= code) && (code <= z);
72-
73-
const [ zero, nine ] = [ 48, 57 ];
74-
const isNumeric = (zero <= code) && (code <= nine);
75-
76-
return isAlpha || isNumeric;
7757
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy