字计数器实施

时间:2010-03-12 03:28:14

标签: c# algorithm

有没有比以下暴力实施c#字计数类更好的方法?

更新代码:抱歉!

/// <summary>
/// A word counting class.
/// </summary>
public class WordCounter
{
    Dictionary<string, int> dictTest = new Dictionary<string, int> ();

    /// <summary>
    /// Enters a word and returns the current number of times that word was found.
    /// </summary>
    /// <param name="word">The word or string found.</param>
    /// <returns>Count of times Found() was called with provided word.</returns>
    public int Found ( string word )
    {
        int count = 1;
        return dictTest.TryGetValue ( word, out count ) ? ++dictTest[word] : dictTest[word] = 1;
    }
}

3 个答案:

答案 0 :(得分:1)

对于matt的回应,Dictionary基本上是带有泛型的HashTable,所以查找是恒定的时间(好吧,不完全相同但是很多)。

答案 1 :(得分:0)

好吧,如果你喜欢很多回忆,你可以将所有字母分别存储在树形结构中。

所以,你有一个包含26个对象的数组,第一个字母是该数组的索引,该数组是一个指向更多26个对象数组的指针数组(但只有当遇到那个字母时才会这样。)等等,第二个字母是第二级数组的索引...

Dictionary是否使用二进制搜索模式?它是否按字符串搜索?或者它是否向下散列字符串,如果没有,则将字符串散列为整数可能提高性能。从理论上讲,如果你手动完成,那么保持列表“排序”就没有任何开销,因为如果它不存在,初始二进制搜索将大致放弃应该在列表中插入的位置?

答案 2 :(得分:0)

您可以构建一个树,然后搜索将在字符串的长度中保持恒定的时间,您正在搜索。在这种情况下,树比使用哈希更节省空间。

相关问题