Skip to content

Instantly share code, notes, and snippets.

@bonomiandreia
Created February 3, 2022 01:15
Show Gist options
  • Save bonomiandreia/c0d939e3e3b4cdf1e4bf20b026f32fe9 to your computer and use it in GitHub Desktop.
Save bonomiandreia/c0d939e3e3b4cdf1e4bf20b026f32fe9 to your computer and use it in GitHub Desktop.
most common word in a string with banned word
function mostCommonWord(paragraph: string, bannedWords?: string[]): string {
let invalid = new Set(["!","?","'",",",";","."," "]);
let banned = new Set(bannedWords);
// set can be a type of a array
let words = new Map();
// map should return values and use set to config new values
let buffer = ""
let result = "";
for(let ptr = 0; ptr < paragraph.length; ptr++) {
// character is valid, append it to the buffer
if (!invalid.has(paragraph[ptr])) {
buffer += paragraph[ptr].toLowerCase();
// unless it is the last character, end this iteration
if (ptr !== paragraph.length) {
continue;
}
}
// character is invalid or is the last one
if (buffer) {
// if the word is not banned, increment it's count
if (!banned.has(buffer)) {
let occurrences = (words.get(buffer) || 0) + 1;
let mostOccurrences = (words.get(result) || 0);
words.set(buffer, occurrences);
if (occurrences > mostOccurrences) {
result = buffer;
}
}
buffer = "";
}
}
console.log(result)
return result;
};
mostCommonWord('Bob hit a ball, the hit BALL flew far after it was hit', ['hit'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment