【发布时间】:2015-06-29 00:02:45
【问题描述】:
在一次采访中,我被要求提出可以容纳数百万个模式的数据结构,并能够快速搜索它们以找到最长匹配的模式。
例如,模式如下:
1- 8876 8893 87 | true
2- 8876 889 | false
3- 8876 8 | false
4- 887 | true
输入是一个至少2位最多18位的数字,我们需要从数据结构中找到最长的匹配模式,并在最后提取布尔值。
例如,8876 8893 9943 53 将匹配 1 并返回 true。 8876 8397 5430 74 将匹配 3 并返回 false。
我的答案是使用一棵树并在每个级别都有一个key value 对列表。键是数字,值是 null 或等于布尔值,具体取决于它是否是模式的结尾。喜欢:
# matching 8875
# start the search by first digit
[..., (7, null), (8, null), (9, null)]
^
[..., (7, null), (8, null), (9, null)]
^
[..., (7, true), (8, null), ...]
# at the last step because we don't have a pattern
# to match the digit 5, we return the `true` from (7, true)
具有挑战性的部分是,模式非常多。数以百万计。这有什么好处吗?如果没有,您的建议是什么。
【问题讨论】:
-
@Alex,纯金人。有时一个词打开了一个新世界。非常感谢。如果您想发布它,我什至会接受而不是作为答案。
-
好的,我将其添加为答案,同时允许问题以接受的答案“关闭”。
标签: algorithm data-structures pattern-matching