-
-
Notifications
You must be signed in to change notification settings - Fork 222
Expand file tree
/
Copy pathvalidPalindrome.js
More file actions
86 lines (77 loc) · 2.13 KB
/
validPalindrome.js
File metadata and controls
86 lines (77 loc) · 2.13 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* Checks if a string is a valid palindrome, considering only alphanumeric characters and ignoring cases.
* @param {string} str
* @returns {boolean}
*/
function isValidPalindrome1(str) {
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;
}
/**
* Checks if a character is alphanumeric.
* @param {string} char
* @returns {boolean}
*/
function isAlphanumeric1(char) {
return /^[a-zA-Z0-9]$/i.test(char);
}
//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(!isAlphanumeric2(ch1)) left++;
else if(!isAlphanumeric2(ch2)) right--;
else {
if(ch1.toLowerCase() != ch2.toLowerCase()) {
return false;
}
left++;
right--;
}
}
return true;
}
/**
* Checks if a character is alphanumeric.
* @param {string} char
* @returns {boolean}
*/
function isAlphanumeric2(char) {
const ch = char.toLowerCase();
return (ch >= 'a' && ch <= 'z')
|| (ch >= '0' && ch <= '9');
}
// Test cases
const testCases = [
{ str: "A man, a plan, a canal: Panama", expected: true },
{ str: "Hello World", expected: false },
{ str: " ", expected: true },
{ str: "racecar", expected: true },
{ str: "No lemon, no melon", expected: true },
{ str: "12321", expected: true },
{ str: "123abccba321", expected: true },
{ str: "abc", expected: false },
];
for (const { str, expected } of testCases) {
const result = isValidPalindrome1(str);
const result1 = isValidPalindrome2(str);
console.log(`Input: "${str}" | Output: ${result} | Expected: ${expected}`);
console.log(`Input: "${str}" | Output: ${result1} | Expected: ${expected}`);
}