String 蛮力字符串模式匹配平均分析

String 蛮力字符串模式匹配平均分析,string,algorithm,pattern-matching,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

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

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()
publicstaticintbrute(字符串文本、字符串模式){
int n=text.length();//n是文本的长度。
int m=pattern.length();//m是图案的长度
int j;

对于(inti=0;i他所指的
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)
,但部分匹配意味着您要么检查了所有
n
,即
O(n)
(找到了完全匹配),要么至少检查了足够多的字符,使其与
n
中的字符数量相等(仅部分匹配)

总的来说,这导致平均时间
O(m+n)

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

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

大多数普通文本搜索的平均值取O(m+n),这是非常重要的 快点

请注意,对于同一个算法,不能有两个大O

看起来你在应用蛮力窗口移位算法

时间=(m-n+1)m

最坏的情况是当m=1时,O(nm)


最好的情况是当你有m=n时,Ω(m)

问平均情况的解释big-O是一个上界。最好的、最坏的和平均情况都可以有上界。因此你可以对它们使用big-O。算法本身也可以有一个上界,这与最坏情况相同。那么,平均使用(非平均情况)是m有Ω(对数(n))