-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid-palindrome.ts
More file actions
44 lines (40 loc) · 1.28 KB
/
Copy pathvalid-palindrome.ts
File metadata and controls
44 lines (40 loc) · 1.28 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
/**
* 125. Valid Palindrome (Easy)
* Link: https://leetcode.com/problems/valid-palindrome/
*
* A phrase is a palindrome if, after lowercasing and removing all non
* alphanumeric characters, it reads the same forward and backward. Return
* whether `s` is a palindrome.
*
* Example:
* Input: s = "A man, a plan, a canal: Panama"
* Output: true
*
* Approach:
* Two pointers from both ends move inward, skipping any non-alphanumeric
* characters, and compare the lowercased letters. A mismatch means not a
* palindrome. This avoids building a cleaned copy of the string.
*
* Time: O(n) — each pointer traverses at most the whole string once.
* Space: O(1) — comparison done in place.
*/
export function isPalindrome(s: string): boolean {
let left = 0;
let right = s.length - 1;
while (left < right) {
while (left < right && !isAlphaNumeric(s[left])) left++;
while (left < right && !isAlphaNumeric(s[right])) right--;
if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}
function isAlphaNumeric(ch: string): boolean {
const code = ch.charCodeAt(0);
return (
(code >= 48 && code <= 57) || // 0-9
(code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) // a-z
);
}