首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在列表中查找相同的模式

在列表中查找相同的模式
EN

Stack Overflow用户
提问于 2012-02-14 01:30:51
回答 3查看 1.4K关注 0票数 0

假设我们有以下列表:

代码语言:javascript
复制
    List<int> Journey1 = new List<int>() { 1, 2, 3, 4, 5 };
    List<int> Journey2 = new List<int>() { 2, 3, 4, 6, 7, 3, 4 };
    List<int> Journey3 = new List<int>() { 6, 7, 1 };
    List<int> Journey4 = new List<int>() { 3, 1, 4 };

这些模式是:

代码语言:javascript
复制
2, 3, 4 -> Journey1, Journey2;
6, 7    -> Journey2, Journey3;
1       -> Journey2, Journey3, Journey4;
5       -> Journey1;
3, 4    -> Journey2;
3       -> Journey4;
4       -> Journey4;

我们有5000个列表,每个列表大约有200个项目,所以模式可以有1-200个项目,可以在1-5000个列表中看到。

因此,我需要非常快的方式进行模式匹配。

EN

回答 3

Stack Overflow用户

发布于 2012-02-14 02:17:09

在没有预计算和简单的即时搜索的情况下:

代码语言:javascript
复制
var matchedJourneys = journeys.Where(x => ContainsPattern(x, mypattern));

bool ContainsPattern(List<int> list, List<int> pattern)
{
    for(int i = 0; i < list.Count - (pattern.Count - 1); i++)
    {
        var match = true;
        for(int j = 0; j < pattern.Count; j++)  
            if(list[i + j] != pattern[j])
                     {
                         match = false;
                         break;
                     }
        if(match) return true;
    }
    return false;
}

这将执行最多2亿个等于检查你的‘数字’。但由于不希望对整个模式执行检查,因此如果检查所有列表,可能需要大约500万次等于操作(只是猜测)。那是几百毫秒。

这完全取决于什么对你来说是“非常快”的。如果这太慢了,你需要一个复杂得多的方法……

票数 2
EN

Stack Overflow用户

发布于 2012-02-14 03:03:47

对于暴力方法,您可以尝试使用polynomial hash-functions来提速子部分匹配。仍然需要大量的比较,但至少匹配可以几乎是恒定的,而不管子序列长度。

票数 0
EN

Stack Overflow用户

发布于 2012-02-16 07:13:40

在您的例子中,有机会从模式预处理和文本预处理(http://en.wikipedia.org/wiki/String_searching_algorithm)中获益。

例如,为列表中的所有子序列构建trie将允许在时间上与模式长度成比例地查询该列表中的给定模式。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9265053

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档