简体   繁体   中英

removing characters from a string - javascript algorithm

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:

  • the last index in the outputString array is "undefined" and I'm not sure why.
  • my output is the right letter, but it's being returned for the length of the original string.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM