forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0125-valid-palindrome.js
57 lines (50 loc) · 1.58 KB
/
0125-valid-palindrome.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* Array - Filter && Clone && Reverse
* Time O(N) | Space O(N)
* https://leetcode.com/problems/valid-palindrome/
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
if (!s.length) return true;
const alphaNumeric = filterAlphaNumeric(s);/* Time O(N) | Space O(N) */
const reversed = reverse(alphaNumeric); /* Time O(N) | Space O(N) */
return alphaNumeric === reversed;
};
const filterAlphaNumeric = (s, nonAlphaNumeric = new RegExp('[^a-z0-9]','gi')) => s
.toLowerCase() /* Time O(N) | Space O(N) */
.replace(nonAlphaNumeric, '')/* Time O(N) | Space O(N) */
const reverse = (s) => s
.split('')/* Time O(N) | Space O(N) */
.reverse()/* Time O(N) | Space O(N) */
.join('');/* Time O(N) | Space O(N) */
/**
* 2 Pointer | Midde Convergence
* Time O(N) | Space O(1)
* https://leetcode.com/problems/valid-palindrome/
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function(s) {
if (s.length <= 1) return true;
let [left, right] = [0, s.length - 1];
let leftChar, rightChar;
while (left < right) {
leftChar = s[left];
rightChar = s[right];
// skip char if non-alphanumeric
if (!/[a-zA-Z0-9]/.test(leftChar)) {
left++;
} else if (!/[a-zA-Z0-9]/.test(rightChar)) {
right--;
} else {
// compare letters
if (leftChar.toLowerCase() != rightChar.toLowerCase()) {
return false;
}
left++;
right--;
}
}
return true;
};