string - 暴力字符串模式匹配平均分析

标签 string algorithm pattern-matching

我有如下的强力字符串模式搜索算法:

public static int brute(String text,String pattern) {
 int n = text.length();    // n is length of text.
 int m = pattern.length(); // m is length of pattern
 int j;
 for(int i=0; i <= (n-m); i++) {
    j = 0;
    while ((j < m) && (text.charAt(i+j) == pattern.charAt(j)) ) {
       j++;
    }
    if (j == m)
     return i;   // match at i
  }
  return -1; // no match
} // end of brute()

作者在分析上述算法时提到了最坏情况和平均情况。

我了解最坏情况下的性能,但对于平均作者如何得出 O(m+n) 性能?此处需要帮助。

在最坏的情况下,蛮力模式匹配的运行时间为 O(mn)。

大多数普通文本搜索的平均时间为 O(m+n),这非常快。

更一般情况的示例: T:“字符串搜索示例是标准的” P:“商店”

感谢您的时间和帮助

最佳答案

他指的 O(m+n) 是在正常情况下会发生的部分匹配。

例如,对于您的正常情况,您将得到:

T: "a string searching example is standard" 
P: "store"

迭代:

 O(38 + 5) == 43
 a -     no match (1)
 space - no match (2)
     s     - match (3)
     t     - match (4)
     r     - no match (5)
 t     - no match (6)
 r     - no match (7)
 i     - no match (8)
 n     - no match (9)
 g     - no match (10)
 space     - no match (11)

等...

我缩进了内部循环以使其更易于理解。

最终您检查了所有 m,即 O(m),但部分匹配意味着您检查了所有 nO(n)(找到完全匹配),或者至少有足够的字符等于 n 中的字符数量(仅部分匹配)。

总体而言,这导致平均 O(m+n) 时间。

最好的情况是 O(n) 如果匹配是在 m 的最开始。

关于string - 暴力字符串模式匹配平均分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15564077/

相关文章:

scala - "case"匿名函数如何在 Scala 中真正工作?

php - 检查字符串是否包含数组的任何值?

C 多维 char 数组 - 赋值从指针生成整数,无需强制转换

C#比较字符串中的字符

c - 递归地查找子集和,产生不正确的输出

algorithm - 打印二叉树的边界

javascript - Switch 中的 ES6 模式匹配

python - 如何检查字符串(变量)是否为空?

algorithm - 查找数字是否为完美正方形的优化方法

java - Java 中的正则表达式分组