给定一个段落 (paragraph) 和一个禁用单词列表 (banned)。返回出现次数最多,同时不在禁用列表中的单词。
题目保证至少有一个词不在禁用列表中,而且答案唯一。
禁用列表中的单词用小写字母表示,不含标点符号。段落中的单词不区分大小写。答案都是小写字母。
示例:
输入:
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
输出: "ball"
解释:
"hit" 出现了3次,但它是一个禁用的单词。
"ball" 出现了2次 (同时没有其他单词出现2次),所以它是段落里出现次数最多的,且不在禁用列表中的单词。
注意,所有这些单词在段落里不区分大小写,标点符号需要忽略(即使是紧挨着单词也忽略, 比如 "ball,"),
"hit"不是最终的答案,虽然它出现次数更多,但它在禁用单词列表中。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/most-common-word
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
public static string MostCommonWord(string paragraph, string[] banned)
{
//过滤一句话中的标点符号
var v = paragraph.Split(' ', ',', '.', '!', '?', ';', '\'');
Dictionary<string, int> dic = new Dictionary<string, int>();
foreach (var item in v)
{
if (!banned.Contains(item.ToLower())&& !string.IsNullOrEmpty(item))
{
if (!dic.ContainsKey(item.ToLower()))
{
dic[item.ToLower()] = 1;
}
else
{
dic[item.ToLower()]++;
}
}
}
string sts= dic.Keys.Max();
//求值最大的key
var max = dic.Aggregate((l, r) => l.Value > r.Value ? l : r).Key;
return max;
}
}
public static void Main(string[] args)
{
MostCommonWord("Bob hit a ball, the hit BALL flew far after it was hit.",
new string[] { "hit" });
}