Leetcode - most-common-word
https://leetcode.com/problems/most-common-word/
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.
Use a map to count every word's frequency.
func mostCommonWord(paragraph string, banned []string) string { paragraph = strings.ToLower(paragraph) para := []byte{} for i := 0; i < len(paragraph); i++ { if isSymbol(paragraph[i]) { para = append(para, ' ') } else { para = append(para, paragraph[i]) } } paragraph = string(para) paras := strings.Split(paragraph, " ") maxWord := "" maxCount := 0 countMap := map[string]int{} bannedMap := map[string]bool{} for _, b := range banned{ bannedMap[b] = true } for i := 0; i < len(paras); i++ { if !bannedMap[paras[i]] && paras[i] != "" { countMap[paras[i]]++ } } for key, val := range countMap { if maxCount < val { maxCount = val maxWord = key } } return maxWord } func isSymbol(b byte) bool { symbols := "!?',;." for i := 0; i < len(symbols); i++ { if symbols[i] == b { return true } } return false }
def most_common_word(paragraph, banned) paragraph.downcase! paragraph.tr!("!?',;.", " ") paras = paragraph.split(" ") banned_hash = {} banned.each {|b| banned_hash[b] = true} hash = {} paras.each do |p| hash[p] = 0 if hash[p].nil? hash[p] += 1 if !banned_hash[p] end max_count = 0 max_word = "" hash.each do |key, val| if val > max_count max_count = val max_word = key end end return max_word end
May 03, 2023 09:23:34 PM
Board Model Paper 2023 Aspirants who had Registered for the Maha Board 12th Class Exam can Download the Previous Paper When Board Announces the Dates to Download the Question Paper. modelpaper2021.in Board Question Papers will be Provided Very Soon Through Online Mode and all the Applicants Should Visit the Official Page Regularly for More Information Regarding Previous Paper, Examination Date. Check the Below Provided Details for More Information About the Board Model Paper.