LeetCode 面试题 16.02. 单词频率

文章目录

  • 一、题目
  • 二、C# 题解

一、题目

  设计一个方法,找出任意指定单词在一本书中的出现频率。

  你的实现应该支持如下操作:

  • WordsFrequency(book) 构造函数,参数为字符串数组构成的一本书
  • get(word) 查询指定单词在书中出现的频率

示例:

WordsFrequency wordsFrequency = new WordsFrequency({“i”, “have”, “an”, “apple”, “he”, “have”, “a”, “pen”});
wordsFrequency.get(“you”); //返回0,"you"没有出现过
wordsFrequency.get(“have”); //返回2,"have"出现2次
wordsFrequency.get(“an”); //返回1
wordsFrequency.get(“apple”); //返回1
wordsFrequency.get(“pen”); //返回1

提示:

  • book[i] 中只包含小写字母
  • 1 <= book.length <= 100000
  • 1 <= book[i].length <= 10
  • get 函数的调用次数不会超过 100000

  点击此处跳转题目。

二、C# 题解

  用哈希表存储查找,直接上代码:

public class WordsFrequency {

    private Dictionary<string, int> dic;

    public WordsFrequency(string[] book) {
        dic = new Dictionary<string, int>();
        foreach (string s in book) {
            if (dic.ContainsKey(s)) dic[s]++;
            else dic[s] = 1;
        }
    }

    public int Get(string word) {
        return dic.GetValueOrDefault(word, 0);
    }
}

/**
 * Your WordsFrequency object will be instantiated and called as such:
 * WordsFrequency obj = new WordsFrequency(book);
 * int param_1 = obj.Get(word);
 */
  • 时间:492 ms,击败 100.00% 使用 C# 的用户
  • 内存:93.49 MB,击败 80.00% 使用 C# 的用户

你可能感兴趣的:(LeetCode写题记录,1024程序员节,c#,leetcode,算法,职场和发展)