3.1.9 #
解答 #
FrequencyCounter 的官方实现:https://algs4.cs.princeton.edu/31elementary/FrequencyCounter.java.html
《双城记》:https://introcs.cs.princeton.edu/java/data/tale.txt
对 FrequencyCounter 做修改,在调用 Put
方法之前,将单词记录在字符串变量 lastPut
中。
在读入单词结束之后输出 lastPut
和 words
变量。
将末尾的版权信息删除后,得到的结果如下:
代码 #
public static string MostFrequentlyWord(string filename, int minLength, ISt<string, int> st)
{
var words = 0;
var sr = new StreamReader(File.OpenRead(filename));
var inputs =
sr
.ReadToEnd()
.Split(new[] { ' ', '\r', '\n' },
StringSplitOptions.RemoveEmptyEntries);
var lastPut = "";
foreach (var s in inputs)
{
if (s.Length < minLength)
continue;
words++;
if (st.Contains(s))
{
lastPut = s;
st.Put(s, st.Get(s) + 1);
}
else
{
lastPut = s;
st.Put(s, 1);
}
}
Console.WriteLine("Last Put: " + lastPut + "\t words count: " + words);
var max = "";
st.Put(max, 0);
foreach (var s in st.Keys())
if (st.Get(s) > st.Get(max))
max = s;
return max;
}