Skip to content

Commit 3475a97

Browse files
committed
solve: Week 03 valid palindrome
1 parent cd5f9f7 commit 3475a97

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

valid-palindrome/eunice-hong.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function isPalindrome(s: string): boolean {
2+
// 1. filter out non-alphanumeric characters
3+
const validChars =
4+
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnlopqrstuvwxyz0123456789";
5+
6+
// 2. compare the first and last characters
7+
let i = 0;
8+
let j = s.length - 1;
9+
10+
while (i < j) {
11+
const head = s[i];
12+
const tail = s[j];
13+
14+
if (!validChars.includes(head)) {
15+
// 3. if the characters are not alphanumeric, move the pointer inward
16+
i++;
17+
} else if (!validChars.includes(tail)) {
18+
// 3. if the characters are not alphanumeric, move the pointer inward
19+
j--;
20+
} else if (head.toLowerCase() !== tail.toLowerCase()) {
21+
// 4. if the characters are not the same, return false
22+
return false;
23+
} else {
24+
// 5. if the characters are the same, move the pointers inward
25+
i++;
26+
j--;
27+
}
28+
}
29+
return true;
30+
}

0 commit comments

Comments
 (0)