-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0125-valid-palindrome.js
More file actions
38 lines (31 loc) · 941 Bytes
/
0125-valid-palindrome.js
File metadata and controls
38 lines (31 loc) · 941 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* Valid Palindrome
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
var isPalindrome = function (s) {
let advanceLeft = 0;
let retreatRight = s.length - 1;
const isCharacterAlphanumeric = (testCharacter) => {
return /^[a-z0-9]$/i.test(testCharacter);
};
while (advanceLeft < retreatRight) {
while (advanceLeft < retreatRight && !isCharacterAlphanumeric(s[advanceLeft])) {
advanceLeft++;
}
while (advanceLeft < retreatRight && !isCharacterAlphanumeric(s[retreatRight])) {
retreatRight--;
}
if (advanceLeft >= retreatRight) {
break;
}
const charAtBeginning = s[advanceLeft].toLowerCase();
const charAtEnding = s[retreatRight].toLowerCase();
if (charAtBeginning !== charAtEnding) {
return false;
}
advanceLeft++;
retreatRight--;
}
return true;
};