日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

LeetCode 819. Most Common Word

發(fā)布時(shí)間:2025/5/22 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 819. Most Common Word 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

原題鏈接在這里:https://leetcode.com/problems/most-common-word/description/

題目:

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.

Note:

  • 1 <= paragraph.length <= 1000.
  • 1 <= 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?!?',;.
  • Different words in?paragraph?are always separated by a space.
  • There are no hyphens or hyphenated words.
  • Words only consist of letters, never apostrophes or other punctuation symbols

題解:

遇到不是letter的char就把當(dāng)前采集到的詞頻率加一. 如果高于目前最大頻率就更換res.

Note: paragraph 本身末位加個(gè)符號(hào). 否則會(huì)丟掉最后一個(gè)詞.

Time Complexity: O(m+n). m = paragraph.length(). n = banned.length.

Space: O(m+n).

AC Java:

1 class Solution { 2 public String mostCommonWord(String paragraph, String[] banned) { 3 HashSet<String> hs = new HashSet<String>(Arrays.asList(banned)); 4 paragraph += '.'; 5 6 String res = ""; 7 int count = 0; 8 HashMap<String, Integer> hm = new HashMap<String, Integer>(); 9 10 StringBuilder sb = new StringBuilder(); 11 for(char c : paragraph.toCharArray()){ 12 if(Character.isLetter(c)){ 13 sb.append(Character.toLowerCase(c)); 14 }else if(sb.length() > 0){ 15 String s = sb.toString(); 16 if(!hs.contains(s)){ 17 hm.put(s, hm.getOrDefault(s, 0)+1); 18 if(hm.get(s) > count){ 19 res = s; 20 count = hm.get(s); 21 } 22 } 23 24 sb = new StringBuilder(); 25 } 26 } 27 28 return res; 29 } 30 }

?

轉(zhuǎn)載于:https://www.cnblogs.com/Dylan-Java-NYC/p/9771565.html

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的LeetCode 819. Most Common Word的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。