-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0125-valid-palindrome.js
More file actions
103 lines (90 loc) · 2.51 KB
/
0125-valid-palindrome.js
File metadata and controls
103 lines (90 loc) · 2.51 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
* 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;
};
/**
* 2 Pointer | Midde Convergence | No RegEx | No Copying
* Time O(N) | Space O(1)
* https://leetcode.com/problems/valid-palindrome/
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
const isAlphaNumeric = (c) =>
(c.toLowerCase() >= 'a' && c.toLowerCase() <= 'z') ||
(c >= '0' && c <= '9');
let left = 0;
let right = s.length - 1;
let skipLeft,
skipRight,
endsEqual = false;
while (left < right) {
skipLeft = !isAlphaNumeric(s.charAt(left));
if (skipLeft) {
left++;
continue;
}
skipRight = !isAlphaNumeric(s.charAt(right));
if (skipRight) {
right--;
continue;
}
endsEqual =
s.charAt(left).toLowerCase() === s.charAt(right).toLowerCase();
if (!endsEqual) return false;
left++;
right--;
}
return true;
};