在干草堆中找到多个针-字符串搜索


find multiple needles in haystack - String Searching

问题:如何在具有亚线性性能的文档的内容体中查找字符串的存在,以及要查找的字符串必须按顺序或其相关id不是字母顺序执行。

最好在PHP和/或JAVA

中解决这个问题

trie或Knuth-Pratt-Morris或boyer-moore实现或其他类似的算法可以帮助在次线性时间内找到这些匹配吗?如果可以,你能告诉我如何。

更多细节

列表长度可以是百万行。每个字符串可以包含字符(a-z0-9)和空白,如"stackoverflow", "stackoverflow"每个String都有一个唯一的整数标识符(id)。{"s":"stackoverflow"、"#":" 920001 "}匹配或找到的字符串应该按照其唯一标识符的顺序找到。同样值得注意。字符串列表不会频繁更改。

*例子

一个字符串数组(920001个唯一字符串)和2个文档示例。检查内容中是否存在列表中的字符串。继续查找匹配,直到找到3个字符串或直到列表耗尽。当在content out中找到字符串时,新数组中的字符串匹配[]

你可以看到字符串"stackoverflow"在列表的最后很长一段路,但是在示例2中,我们只匹配字符串,其中一个是stackoverflow,它将花费相当多的时间来匹配使用简单的循环和匹配字符串数组。

出于此目的,请将下面的列表视为有920001行,并且在12到920000行之间的字符串不包含任何匹配。

**示例列表

"strings":[
    {"s":"Disney World", "#":"1"}, 
    {"s":"Universal Studios", "#":"2"}, 
    {"s":"Disneyland", "id":"3"}, 
    {"s":"Slide", "id":"4"}, 
    {"s":"Disneyland", "id":"5"}, 
    {"s":"Plane", "id":"6"}, 
    {"s":"Walt Disney World", "#":"7"}, 
    {"s":"Florida", "#":"8"}, 
    {"s":"Puerto Rico", "#":"9"}, 
    {"s":"Dominican Republic", "id":"10"}, 
    {"s":"Las Vegas", "#":"11"},
    {"s":"Mexico", "#":"12"}
    ....
    ....
    {"s":"United States", "#":"920000"}
    {"s":"stackoverflow", "#":"920001"}
]

**内容示例

content = "Bordered on the west by the Gulf of Mexico and on the east by the Atlantic Ocean, Florida has the longest coastline in the contiguous United States and its geography is dominated by water and the threat of frequent hurricanes. Whether you’re a native or just visiting stackoverflow"
content ="tourist attractions and amusement parks. Slide to the seaside hot spots and abundant nightlife, what you need to stay on top of all of the new developments in the Panhandle State today stackoverflow"
在我看来,这就是问题所在。

为你的内容建立一个后缀树(合并每个内容的所有后缀树),然后在这个后缀树中搜索你的字符串

如果你使用Ukkonen的算法,它是线性的(=O(n+m)其中n是你的内容的大小,m是你的字符串的大小)。

你不能实现亚线性的性能,因为你需要读取所有匹配的内容至少一次。