-
-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathvalidPalindrome.js
58 lines (50 loc) · 1.44 KB
/
validPalindrome.js
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
//Two pointer:- TC:O(n) SC: O(n)
function isValidPalindrome1(str) {
if(str.length <=1) return true;
let left = 0, right = str.length -1;
while(left <= right) {
let ch1 = str[left];
let ch2 = str[right];
if(!isAlphanumeric(ch1)) left++;
else if(!isAlphanumeric(ch2)) right--;
else {
if(ch1.toLowerCase() != ch2.toLowerCase()) {
return false;
}
left++;
right--;
}
}
return true;
}
//Two pointer without regex:- TC:O(n) SC: O(n)
function isValidPalindrome2(str) {
if(str.length <=1) return true;
let left = 0, right = str.length -1;
while(left <= right) {
let ch1 = str[left];
let ch2 = str[right];
if(!isAlphanumeric1(ch1)) left++;
else if(!isAlphanumeric1(ch2)) right--;
else {
if(ch1.toLowerCase() != ch2.toLowerCase()) {
return false;
}
left++;
right--;
}
}
return true;
}
function isAlphanumeric(char) {
return /[a-zA-Z0-9]/.test(char);
}
function isAlphanumeric1(char) {
return (char.toLowerCase() >= 'a' && char.toLowerCase() <= 'z') || (char >= '0' && char <= '9');
}
let str1 ="A man, a plan, a canal: Panama";
console.log(isValidPalindrome1(str1));
console.log(isValidPalindrome2(str1));
let str2 ="Hello World";
console.log(isValidPalindrome1(str2));
console.log(isValidPalindrome2(str2));