Skip to content

Commit 2b0d5b7

Browse files
committed
feat: add valid palindrome solution
1 parent ae39686 commit 2b0d5b7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

typescript/src/validPalindrome/README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ Since an empty string reads the same forward and backward, it is a palindrome.
3434
## Solution
3535

3636
```typescript
37+
// Solution 1
3738
function isPalindrome(s: string): boolean {
3839
// Remove all characters except letters and numbers and convert to lowercase
3940
const cleanedString = s.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
@@ -53,6 +54,41 @@ function isPalindrome(s: string): boolean {
5354

5455
return true;
5556
}
57+
58+
// Solution 2
59+
function isPalindrome(s: string): boolean {
60+
// Function to check if a character is a letter or a digit
61+
function isAlphanumeric(char: string): boolean {
62+
const charCode = char.charCodeAt(0);
63+
return (
64+
(charCode >= 48 && charCode <= 57) || // Numbers 0-9
65+
(charCode >= 65 && charCode <= 90) || // Letters A-Z
66+
(charCode >= 97 && charCode <= 122) // Letters a-z
67+
);
68+
}
69+
70+
// Remove all characters except letters and numbers and convert the string to lowercase
71+
let cleanedString = "";
72+
for (let i = 0; i < s.length; i++) {
73+
if (isAlphanumeric(s[i])) {
74+
cleanedString += s[i].toLowerCase();
75+
}
76+
}
77+
78+
// Checking if the string being cleared is a palindrome
79+
let left = 0;
80+
let right = cleanedString.length - 1;
81+
82+
while (left < right) {
83+
if (cleanedString[left] !== cleanedString[right]) {
84+
return false;
85+
}
86+
left++;
87+
right--;
88+
}
89+
90+
return true;
91+
}
5692
```
5793

5894
## Complexity Analysis

0 commit comments

Comments
 (0)