I'm practicing algorithm problems and am trying to remove given letters from a string in o(n) time.
My attempt below is wrong in a couple of ways:
How can I fix these and why are these errors occurring?
function removeChars(lettersToDelete, string) {
var flags = {}; // a hash of letters to delete.
var outputString = string.split("");
var lettersToDelete = lettersToDelete.split("");
var i, j;
for (i = 0; i < lettersToDelete.length; i++) {
flags[lettersToDelete[i]] = true;
}
console.log(flags);
for (var j = 0; j < string.length; j++) {
if (flags[string[j]]) {
outputString[j++] = string[j];
}
}
console.log(outputString); //[ 'a', 'a', 'a', 'a', undefined ]
return outputString.join(""); // 'aaaa'
}
function removeChars(lettersToDelete, string) { var flags = {}; // a hash of letters to delete. var outputString = []; //string.split(""); var lettersToDelete = lettersToDelete.split(""); var i, j; for (i = 0; i < lettersToDelete.length; i++) { flags[lettersToDelete[i]] = true; } for (var j = 0; j < string.length; j++) { if (!flags[string[j]]) { outputString.push( string[j] ); } } console.log(outputString); return outputString.join(""); // 'aaaa' } removeChars("itu", "mitul");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.