File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
typescript/src/validPalindrome Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -34,6 +34,7 @@ Since an empty string reads the same forward and backward, it is a palindrome.
34
34
## Solution
35
35
36
36
``` typescript
37
+ // Solution 1
37
38
function isPalindrome(s : string ): boolean {
38
39
// Remove all characters except letters and numbers and convert to lowercase
39
40
const cleanedString = s .replace (/ [^ a-zA-Z0-9 ] / g , " " ).toLowerCase ();
@@ -53,6 +54,41 @@ function isPalindrome(s: string): boolean {
53
54
54
55
return true ;
55
56
}
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
+ }
56
92
```
57
93
58
94
## Complexity Analysis
You can’t perform that action at this time.
0 commit comments