python - 高效的字符串算法——正则匹配

标签 python regex string algorithm data-structures

问题陈述:

Given two list A of strings and B of regex's(they are string too).
For every regex in list B, find all the matching strings in list A.
Length of list A <= 10^6 (N)
Length of string B <= 100 (M)
Length of strings, regex <= 30 (K)
Assume regex matching and string comparisons take O(K) time and regex can contain any python regex supported operations.

我的算法:

for regex in B:
    for s in A:
        if regex.match(s):
            mapping[regex].add(s)

这需要 O(N*M*K) 时间。
有什么方法可以在牺牲空间(使用任何数据结构)的情况下提高时间效率吗?

最佳答案

就时间复杂度而言,这已经是最快的速度了。

每个正则表达式必须与每个字符串至少匹配一次。否则,您将无法获取“匹配”或“不匹配”的信息。

在绝对时间方面,你可以使用filter避免缓慢的 Python 循环:

mapping = {regex: filter(re.compile(regex).match, A) for regex in B}

关于python - 高效的字符串算法——正则匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44737397/

相关文章:

c++ - 用空格格式化字符串

python - 如何在处理前从字符串中去除额外的句号 (.) 或清理数据?

java - 从java中的字符串中获取整数

javascript - 如何检查字符串在JavaScript中的任何点是否包含字符

javascript - 正则表达式:排除单词,但包括非标准标点

android - 麻省理工学院 AppInventor : How to handle a large list?

python - 检查 numpy 数组中的不变列

python - 如何将所有 conda 环境放入一个文件夹

python - 如何使用 Google App Engine sdk 在本地 2 个应用程序之间共享内存缓存项目

python - Python中的匹配组