-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution819.cs
58 lines (52 loc) · 1.55 KB
/
Solution819.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution819
{
/// <summary>
/// 819. Most Common Word - Easy
/// <a href="https://leetcode.com/problems/most-common-word">See the problem</a>
/// </summary>
public string MostCommonWord(string paragraph, string[] banned)
{
var bannedSet = new HashSet<string>(banned);
var wordCount = new Dictionary<string, int>();
var maxCount = 0;
var mostCommonWord = string.Empty;
var word = new StringBuilder();
foreach (var c in paragraph)
{
if (char.IsLetter(c))
{
word.Append(char.ToLower(c));
}
else if (word.Length > 0)
{
var w = word.ToString();
if (!bannedSet.Contains(w))
{
wordCount[w] = wordCount.GetValueOrDefault(w, 0) + 1;
if (wordCount[w] > maxCount)
{
maxCount = wordCount[w];
mostCommonWord = w;
}
}
word.Clear();
}
}
if (word.Length > 0)
{
var w = word.ToString();
if (!bannedSet.Contains(w))
{
wordCount[w] = wordCount.GetValueOrDefault(w, 0) + 1;
if (wordCount[w] > maxCount)
{
mostCommonWord = w;
}
}
}
return mostCommonWord;
}
}