-
Notifications
You must be signed in to change notification settings - Fork 0
/
valid-palindrome.ts
50 lines (41 loc) · 1.08 KB
/
valid-palindrome.ts
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
/*
A phrase is a palindrome if, after converting all uppercase letters into lowercase
letters and removing all non-alphanumeric characters, it reads the same forward and backward.
Alphanumeric characters include letters and numbers.
Given a string s, return true if it is a palindrome, or false otherwise.
Constraints:
1 <= s.length <= 2 * 105
s consists only of printable ASCII characters.
*/
const EXAMPLES = [
{
input: 'A man, a plan, a canal: Panama',
output: true,
},
{
input: 'race a car',
output: false,
},
{
input: ' ',
output: true,
},
];
/** Time O(n) | Space O(n) */
function isValidPalindrome(str: string): boolean {
const sanitized = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
for (let i = 0; i < str.length; i++) {
if (sanitized[i] !== sanitized[sanitized.length - 1 - i]) {
return false;
}
}
return true;
}
if (import.meta.vitest) {
const { it, expect } = import.meta.vitest;
it(() => {
EXAMPLES.forEach((example) => {
expect(isValidPalindrome(example.input)).toEqual(example.output);
});
});
}