【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是最長單詞長度。
相關文章
- 508-Most Frequent Subtree Sum
- The most influential person
- [Most.js] Create Streams From Single Values With Most.jsJS
- *692. Top K Frequent Words
- Leetcode 347. Top K Frequent ElementsLeetCode
- Leetcode 11 Container With Most WaterLeetCodeAI
- H. The Most Reckless Defense
- Traceback (most recent call last):AST
- 347. Top K Frequent Elements - Bucket Sorting
- LeetCode 11. Container With Most WaterLeetCodeAI
- leetcode_11. Container With Most WaterLeetCodeAI
- [LintCode] Daily TemperaturesAI
- [LintCode] Permutation in String
- 【Leetcode】1673. Find the Most Competitive SubsequenceLeetCode
- LeetCode - Medium - 11. Container With Most WaterLeetCodeAI
- [LintCode/LeetCode] Meeting RoomsLeetCodeOOM
- Lintcode 1263. Is Subsequence
- 【Lintcode】1189. Minesweeper
- The Buffalo Bills may be the third most popular team in their nation
- LeetCode Container With Most Water(011)解法總結LeetCodeAI
- [LeetCode] 2070. Most Beautiful Item for Each QueryLeetCode
- 什麼是MOST商業分析技術?
- [LeetCode/LintCode] Largest Palindrome ProductLeetCode
- [LintCode/LeetCode] Contains Duplicate IIILeetCodeAI
- [LintCode] Check Full Binary Tree
- [LintCode/LeetCode] Remove Duplicate LettersLeetCodeREM
- [LintCode] 3Sum Smaller
- 【Lintcode】1615. The Result of Investment
- [LintCode] Binary Tree Level Order
- 【Lintcode】1736. Throw Garbage
- 【Lintcode】1665. Calculate Number
- 【Lintcode】1789. Distinguish UsernameNGUI
- 【Lintcode】1562. Number of RestaurantsREST
- 【Lintcode】576. Split Array
- 【Lintcode】1267. Lexicographical Numbers
- 【Lintcode】141. Sqrt(x)
- 【Lintcode】1415. Residual Product
- 【Lintcode】1230. Assign CookiesCookie