The task:
Given a string which we can delete at most k, return whether you can make a palindrome.
For example, given 'waterrfetawx' and a k of 2, you could delete f and x to get 'waterretaw'.
The following solution is partially inspired by @Oh My Goodness's answer.
const s = "waterrfetawx";
const del = 2;
function palindromePossible(str, deleteAtMost) {
const set = new Set();
for (let i = 0, len = str.length; i < len; i++) {
const char = str[i];
void(set.delete(char) || set.add(char)); // <--is this good code?
}
let iStart = 0, iEnd = str.length - 1, possibleDeletion = 0;
function isSame() {
do {
if (str[iStart] === str[iEnd]) {
iStart++;
iEnd--;
return true;
}
if (++possibleDeletion > deleteAtMost) { return false; }
if (set.has(str[iStart])) { iStart++; }
if (set.has(str[iEnd])) { iEnd--; }
if (iStart > iEnd) { return false; }
} while(str[iStart] !== str[iEnd]);
return true;
}
if (set.size <= deleteAtMost + 1) {
for (let i = 0, len = Math.floor(str.length/2); i < len && iStart <= iEnd; i++) {
if (!isSame()) { return false; }
}
return true;
}
return false;
}
console.log(palindromePossible(s, del));
1 Answer 1
You have a question embedded in the code:
void(set.delete(char) || set.add(char)); // <--is this good code?
The void operator "evaluates the given expression and then returns undefined
"1 . It doesn't appear that there is a need to have undefined
be the final value of that expression because that expression doesn't get assigned or returned. The void()
can be removed without changing the functionality of the code. I wouldn't say it is bad code, but unnecessary.
That for
loop could be simplified:
for (let i = 0, len = str.length; i < len; i++) { const char = str[i]; void(set.delete(char) || set.add(char)); // <--is this good code? }
using a for...of
loop:
for (const char of str) {
set.delete(char) || set.add(char);
}
1https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void
Explore related questions
See similar questions with these tags.
palindromePossible("waterrfetawx", 1)
returnstrue
. AKA shouldn'tdeleteAtMost + 1
just bedeleteAtMost
? \$\endgroup\$waterfretawx
and then delete thex
.waterfretaw
can the be read forward and backwards @Shelby115 \$\endgroup\$