|
1 | | -const tokensToRemove = /[.,:;?!\s]/g |
| 1 | +// Characters to remove from string in order to normalize it |
| 2 | +const charsToRemove = /[.,:;?!\s]/g |
2 | 3 |
|
3 | 4 | /** |
4 | | - * Remove tokens and convert to lowercase. |
| 5 | + * Checks if a string is a palindrome. |
| 6 | + * |
| 7 | + * Time complexity: O(n) |
| 8 | + * Space complexity: O(n) |
5 | 9 | * |
6 | | - * @private |
7 | | - * @param {string} str String to normalize |
8 | | - * @returns {string} Normalized string. |
| 10 | + * @param {string} str String to be checked. |
| 11 | + * @returns {boolean} Whether the string is a palindrome. |
9 | 12 | */ |
10 | | -const normalize = (str) => |
11 | | - str |
12 | | - .replace(tokensToRemove, '') |
| 13 | +const isPalindrome = (str) => { |
| 14 | + const normalStr = str |
| 15 | + .replace(charsToRemove, '') |
13 | 16 | .toLowerCase() |
14 | 17 |
|
15 | | -/** |
16 | | - * Reverse the order of characters. |
17 | | - * |
18 | | - * @param {string} str String to reverse. |
19 | | - * @returns {string} Reversed string. |
20 | | - */ |
21 | | -const reverse = (str) => |
22 | | - [...str] |
| 18 | + const reverseNormalStr = [...normalStr] |
23 | 19 | .reverse() |
24 | 20 | .join('') |
25 | 21 |
|
26 | | -/** |
27 | | - * Checks if a string is a palindrome. |
28 | | - * Complexity: time O(n) because normalize and reverse always happen, |
29 | | - * space O(n). |
30 | | - * @param {string} str String to be checked. |
31 | | - * @returns {boolean} True if the string is a palindrome, false otherwise. |
32 | | - */ |
33 | | -const isPalindrome = (str) => { |
34 | | - const normalStr = normalize(str) |
35 | | - return normalStr === reverse(normalStr) |
| 22 | + return normalStr === reverseNormalStr |
36 | 23 | } |
37 | 24 |
|
38 | 25 | module.exports = { |
|
0 commit comments