【Lintcode】1484. The Most Frequent Word
題目地址:
https://www.lintcode.com/problem/the-most-frequent-word/description
給定一個英文句子 s s s,其由若干由空格分隔的單片語成,單詞的末尾可能跟了一個標點符號。問出現次數最多的單詞是哪個。另外會給定一個雜湊表,儲存的是不參與統計的單詞。
先對 s s s按空格split,然後用一個雜湊表統計每個單詞出現的次數。統計的時候注意單詞的最後一個字元是否是標點符號。程式碼如下:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Solution {
/**
* @param s: a string
* @param excludewords: a dict
* @return: the most frequent word
*/
public String frequentWord(String s, Set<String> excludewords) {
// Write your code here
String res = "";
Map<String, Integer> map = new HashMap<>();
String[] strs = s.split(" ");
for (int i = 0; i < strs.length; i++) {
String str = strs[i];
if (!Character.isLetter(str.charAt(str.length() - 1))) {
str = str.substring(0, str.length() - 1);
}
if (!excludewords.contains(str)) {
map.put(str, map.getOrDefault(str, 0) + 1);
}
}
int maxCount = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
if (res.isEmpty()) {
res = entry.getKey();
maxCount = entry.getValue();
continue;
}
if (entry.getValue() > maxCount) {
res = entry.getKey();
maxCount = entry.getValue();
} else if (entry.getValue() == maxCount) {
if (entry.getKey().compareTo(res) < 0) {
res = entry.getKey();
}
}
}
return res;
}
}
時空複雜度 O ( n l ) O(nl) O(nl), n n n是單詞個數, l l l是最長單詞長度。
相關文章
- LintCode-Word SegmentationSegmentation
- LintCode-Word Search II
- *692. Top K Frequent Words
- 347. Top K Frequent Elements
- Spark FPGrowth (Frequent Pattern Mining)Spark
- [Most.js] Create Streams From Single Values With Most.jsJS
- Front Most Alfred WorkflowAlfred
- The most influential person
- LeetCode-Top K Frequent ElementsLeetCode
- Traceback (most recent call last):AST
- H. The Most Reckless Defense
- 347. Top K Frequent Elements - Bucket Sorting
- Leetcode 347. Top K Frequent ElementsLeetCode
- UVA 11235-Frequent values(RMQ)MQ
- 11. Container With Most WaterAI
- Afterall most women on quite a few skillUI
- leetcode Container With Most WaterLeetCodeAI
- Although it does not provide the most Parajumpers On SaleIDE
- POJ 3368 Frequent values (UVA 11235)(RMQ)MQ
- [LintCode] Daily TemperaturesAI
- LintCode 子樹
- LintCode-Backpack
- LintCode-HeapifyAPI
- Leetcode 11 Container With Most WaterLeetCodeAI
- Leetcode-Container With Most WaterLeetCodeAI
- Container With Most Water leetcode javaAILeetCodeJava
- You are beautiful voted the 'Most Irritating Song Ever'.
- 什麼是MOST商業分析技術?
- leetcode_11. Container With Most WaterLeetCodeAI
- LeetCode 11. Container With Most WaterLeetCodeAI
- [LintCode] Permutation in String
- LintCode 主元素 II
- LintCode 解碼方法
- LintCode-Search for a Range
- LintCode-K Sum
- LintCode-Hash FunctionFunction
- LintCode-Fast PowerAST
- Lintcode-Max Tree