# 819 Most Common Word

原來 split 也可以用 regex, split(/[^a-z]/) / 有些題型 forEach 一次就全部搞定了 / 若題目要求次數可以直接 max ,但因為要求哪字串所以要多一個 result

LeetCode

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.

input: 一串字
output: 找出出現最多的 word, 不能是 banned,不管大小寫跟標點符號 "ball"  = "ball," = "Ball"
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.
 

Note:

1 <= paragraph.length <= 1000.
0 <= banned.length <= 100.
1 <= banned[i].length <= 10.
The answer is unique, and written in lowercase (even if its occurrences in paragraph may have uppercase symbols, and even if it is a proper noun.)
paragraph only consists of letters, spaces, or the punctuation symbols !?',;.
There are no hyphens or hyphenated words.
Words only consist of letters, never apostrophes or other punctuation symbols.
*/

/**
 * @param {string} paragraph
 * @param {string[]} banned
 * @return {string}
 */
var mostCommonWord = function(paragraph, banned) {}

Edge Case

  • banned 可能有很多個

如何解

用 Map 存字串跟出現幾次,需要去除 banned 裡面的值.若題目要求次數可以直接 max ,但因為要求哪字串所以要多一個 result

if(max < myMap.get(word)){
    max = myMap.get(word);
    result = word;
}

Code

var mostCommonWord = function(paragraph, banned) {
    // 轉小寫跟不管標點符號
    let arr = paragraph.toLowerCase().split(/[^a-z]/);
    let myMap = new Map();
    let mySet = new Set(banned);
    let max = 0;
    let result = "";

    arr.forEach(word => {
        if(!mySet.has(word) && word != ''){
            myMap.set(word, myMap.has(word) ? myMap.get(word) + 1 : 1);
            if(max < myMap.get(word)){
                max = myMap.get(word);
                result = word;
            }
        }
    })
    return result
};


// console.log(mostCommonWord("Bob. hIt, b,b,baLl", ["Bob, hit"]))
console.log(mostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]))

學到什麼

注意看這塊,我就是忽略才以為 banned 只是一個字串而已

/**
 * @param {string} paragraph
 * @param {string[]} banned
 * @return {string}
 */

Last updated