Skip to content

Commit 81ba9a5

Browse files
committed
Valid Palindrome
1 parent c8e4168 commit 81ba9a5

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

0125_validPalindrome.js

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @param {string} s
3+
* @return {boolean}
4+
*/
5+
6+
/**
7+
* @param {strng} s string to check if palindrome
8+
* @return {boolean} True if string is a palindrome (only counting alphanumeric chars).
9+
* @summary Valid palindrome {@link https://leetcode.com/problems/valid-palindrome/}
10+
* @description Given an input string, return true if its a palindrome (non-alphanumeric chars excluded);
11+
* Space O(1) - No extra space (few variables).
12+
* Time O(n) - Traverse over the input string.
13+
*/
14+
const isPalindrome = s => {
15+
if (!s) return true;
16+
17+
const isAlphanumeric = c =>
18+
(code >= 'a'.charCodeAt() && code <= 'z'.charCodeAt()) || (code >= '0'.charCodeAt() && code <= '9'.charCodeAt());
19+
20+
let left = 0;
21+
let right = s.length - 1;
22+
const mid = Math.ceil(s.length / 2);
23+
24+
while (left <= right) {
25+
const leftChar = s[left].toLowerCase();
26+
const rightChar = s[right].toLowerCase();
27+
28+
const isLeftValid = isAlphanumeric(leftChar.charCodeAt());
29+
const isRightValid = isAlphanumeric(rightChar.charCodeAt());
30+
31+
if (isLeftValid && isRightValid && leftChar !== rightChar) return false;
32+
33+
if (!isLeftValid && isRightValid) left++;
34+
else if (isLeftValid && !isRightValid) right--;
35+
else {
36+
left++;
37+
right--;
38+
}
39+
}
40+
41+
return true;
42+
};

0 commit comments

Comments
 (0)