-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path125-valid-palindrome.js
More file actions
60 lines (49 loc) · 1.43 KB
/
Copy path125-valid-palindrome.js
File metadata and controls
60 lines (49 loc) · 1.43 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
var isPalindrome = function (s) {
const isNumber = (code) => code >= 48 && code <= 57;
const isAlpha = (code) => code >= 97 && code <= 122;
let left = 0, right = s.length - 1;
while(right > left) {
const leftCode = s[left].toLowerCase().charCodeAt(0);
if (!isNumber(leftCode) && !isAlpha(leftCode)) {
left++;
continue;
}
const rightCode = s[right].toLowerCase().charCodeAt(0);
if (!isNumber(rightCode) && !isAlpha(rightCode)) {
right--;
continue;
}
if (leftCode !== rightCode) {
return false;
}
left++;
right--;
}
return true;
};
var isPalindrome2 = function (s) {
let sanitized = '';
let reversed = '';
for(let i =0 ; i < s.length; i++) {
const code = s[i].toLowerCase().charCodeAt(0), isNumber = code >= 48 && code <= 57, isAlpha = code >= 97 && code <= 122;
if (!isNumber && !isAlpha) {
continue;
}
const char = String.fromCharCode(code);
sanitized += char;
reversed = char + reversed;
}
return sanitized === reversed;
};
const data = [
{ s: "A man, a plan, a canal: Panama", output: true },
{ s: "race a car", output: false },
{ s: " ", output: true },
];
for (let d of data) {
console.log(JSON.stringify(d));
const result = isPalindrome(d.s);
console.log('result = ', result);
(JSON.stringify(result) === JSON.stringify(d.output)) ? console.log('ok') : console.error('nok');
console.log('----------');
}