codebuddies / DailyAlgorithms

Do a problem. Create (or find) your problem in the issues. Paste a link to your solution. See others' solutions of the same problem.
12 stars 1 forks source link

[Leetcode] Most Common Word #44

Open lpatmo opened 5 years ago

lpatmo commented 5 years ago

Given a paragraph and a list of banned words, return the most frequent word that is not in the list of banned words. It is guaranteed there is at least one word that isn't banned, and that the answer is unique.

Words in the list of banned words are given in lowercase, and free of punctuation. Words in the paragraph are not case sensitive. The answer is in lowercase.

Example:

Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit." banned = ["hit"] Output: "ball" Explanation: "hit" occurs 3 times, but it is a banned word. "ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph. Note that words in the paragraph are not case sensitive, that punctuation is ignored (even if adjacent to words, such as "ball,"), and that "hit" isn't the answer even though it occurs more because it is banned.

lpatmo commented 5 years ago

var mostCommonWord = function(paragraph, banned) {
    //lowercase the paragraph and clean it of punctuation
    //clean the paragraph of banned words
    //frequency count the appearance of banned words
    let paragraphCleaned = paragraph.toLowerCase();
    console.log('paraStr: ', paragraphCleaned)

    // banned.forEach((bannedWord) => {
    //     paragraphCleaned = paragraphCleaned.split(bannedWord).join("").replace(/  /g, ' ');
    // })
    console.log('paragraphCleaned: ', paragraphCleaned)

    const paragraphArr = [];
    let buildWord = "";
    let alphabet = "abcdefghijklmnopqrstuvwxyz";
    for (let i=0; i< paragraphCleaned.length; i++) {
        if (alphabet.indexOf(paragraphCleaned[i]) > -1) {
            buildWord+=paragraphCleaned[i];
        } else {
            if (buildWord.length > 0) {
                paragraphArr.push(buildWord);
                buildWord = "";
            }
        }
    }
    if (buildWord.length > 0) {
        paragraphArr.push(buildWord);
    }
    console.log(paragraphArr)
    let freq = paragraphArr.reduce((acc, word) => {
        if (acc[word]) {
            acc[word] += 1;
        } else {
            acc[word] = 1;
        }
        return acc;
    }, {});
    console.log(freq)
    let max = 0;
    let output;
    for (let key in freq) {
        if (freq[key] > max) {
          if (key !== '' && !banned.includes(key)) {
            max = freq[key];
            output = key;
          }
        }
    }
    return output;
};