本文共 1640 字,大约阅读时间需要 5 分钟。
给定一个英文句子 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, Setexcludewords) { // Write your code here String res = ""; Map 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 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是最长单词长度。
转载地址:http://bwjs.baihongyu.com/