【发布时间】:2021-03-07 00:03:32
【问题描述】:
我遇到了以下编程面试问题:
挑战 1:N-gram
N-gram 是来自给定单词的 N 个连续字符的序列。对于“pilot”这个词有三个 3-gram:“pil”、“ilo”和“lot”。 对于给定的一组单词和一个 n-gram 长度 你的任务是
• write a function that finds the n-gram that is the most frequent one among all the words
• print the result to the standard output (stdout)
• if there are multiple n-grams having the same maximum frequency please print the one that is the smallest lexicographically (the first one according to the dictionary sorting order)
请注意,您的函数将接收以下参数:
• text
○ which is a string containing words separated by whitespaces
• ngramLength
○ which is an integer value giving the length of the n-gram
数据约束
• the length of the text string will not exceed 250,000 characters
• all words are alphanumeric (they contain only English letters a-z, A-Z and numbers 0-9)
效率限制
• your function is expected to print the result in less than 2 seconds
示例 输入 文本:“aaaab a0a baaab c”
输出 aaa ngramLength: 3
解释
对于上面显示的输入,按频率排序的 3-gram 是:
• "aaa" with a frequency of 3
• "aab" with a frequency of 2
• "a0a" with a frequency of 1
• "baa" with a frequency of 1
如果我只有一小时的时间来解决这个问题并且我选择使用 C 语言来解决它:实现一个哈希表来计算 N-gram 在这段时间内出现的频率是一个好主意吗?因为在 C 库中没有哈希表的实现...
如果是,我正在考虑使用带有有序链表的单独链接来实现哈希表。这些实现减少了您必须解决问题的时间......
这是最快的选择吗?
谢谢!!!
【问题讨论】:
-
这是真正的编码面试吗?
-
您确定二叉树(例如 AVL)无法完成这项工作吗?
-
你会被要求最多 3 克吗?有 (26+26+10)^3 = 238328 个可能只有字母数字字符的 3-gram,因此直接 LUT 看起来是可行的。
-
我会提前在一个数组中分配所需数量的桶(这是可能的,因为你有文本长度的上限),并且只将指向它们的指针存储在哈希中桌子。使用移动到前面/在后面的启发式插入以使哈希表检索更快。并在最后对数组进行排序。在实践中使用树会比较慢。
-
想一想。在 1000 个字符的文本中,有多少个 3-gram?