Skip to content

Commit c500c6c

Browse files
committed
feat: write charset based solution
1 parent 204f548 commit c500c6c

File tree

3 files changed

+50
-3
lines changed

3 files changed

+50
-3
lines changed

src/interview-classics/is-palindrome/is-palindrome-while.js src/interview-classics/is-palindrome/is-palindrome-while-regex.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
const charsToIgnore = /[-.,:;?!'"\s()]/
33

44
/**
5-
* Checks if a string is a palindrome. Uses a while loop.
5+
* Checks if a string is a palindrome. Uses a while loop and a regular
6+
* expression.
67
*
78
* Time complexity: O(n)
89
* Space complexity: O(1)
@@ -40,5 +41,5 @@ const isPalindrome = (str) => {
4041

4142
module.exports = {
4243
fun: isPalindrome,
43-
id: 'while-loop'
44+
id: 'while-loop regex'
4445
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Characters to remove from string in order to normalize it
2+
const charsToIgnore = new Set(['-', '.', ',', ':', ';', '?', '!', "'", '"',
3+
'\n', ' ', '(', ')'])
4+
5+
/**
6+
* Checks if a string is a palindrome. Uses a while loop and set of characters.
7+
*
8+
* Time complexity: O(n)
9+
* Space complexity: O(1)
10+
*
11+
* @param {string} str String to be checked.
12+
* @returns {boolean} Whether the string is a palindrome.
13+
*/
14+
const isPalindrome = (str) => {
15+
let leftIdx = 0
16+
let rightIdx = str.length - 1
17+
18+
while (leftIdx < rightIdx) {
19+
// Skip left characters that are in the ignore regex
20+
while (charsToIgnore.has(str[leftIdx])) {
21+
leftIdx++
22+
}
23+
24+
// Skip right characters that are in the ignore regex
25+
while (charsToIgnore.has(str[rightIdx])) {
26+
rightIdx--
27+
}
28+
29+
// Different characters, not a palindrome
30+
if (str[leftIdx].toLowerCase() !== str[rightIdx].toLowerCase()) {
31+
return false
32+
}
33+
34+
// Equal characters, continue to next characters
35+
leftIdx++
36+
rightIdx--
37+
}
38+
39+
return true
40+
}
41+
42+
module.exports = {
43+
fun: isPalindrome,
44+
id: 'while-loop char-set'
45+
}
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const solutions = [
22
require('./is-palindrome-method'),
3-
require('./is-palindrome-while')
3+
require('./is-palindrome-while-regex'),
4+
require('./is-palindrome-while-set')
45
]
56

67
module.exports = solutions

0 commit comments

Comments
 (0)