字符串匹配问题的形式定义:

  • 文本(Text)是一个长度为 n 的数组 T[1..n];
  • 模式(Pattern)是一个长度为 m 且 m≤n 的数组 P[1..m];
  • T 和 P 中的元素都属于有限的字母表 Σ 表
  • 如果 0≤s≤n-m,并且 T[s+1..s+m] = P[1..m],即对 1≤j≤m,有 T[s+j] = P[j],则说模式 P 在文本 T 中出现且位移为 s,且称 s 是一个有效位移(Valid Shift)

比如上图中,目标是找出所有在文本 T = abcabaabcabac 中模式 P = abaa 的所有出现。该模式在此文本中仅出现一次,即在位移 s = 3 处,位移 s = 3 是有效位移。

解决字符串匹配的算法包括:朴素算法(Naive Algorithm)、Rabin-Karp 算法、有限自动机算法(Finite Automation)、 Knuth-Morris-Pratt 算法(即 KMP Algorithm)、Boyer-Moore 算法、Simon 算法、Colussi 算法、Galil-Giancarlo 算法、Apostolico-Crochemore 算法、Horspool 算法、Shift-Or 算法和 Sunday 算法等。本文中我们将主要介绍 Boyer-Moore 算法(即 BM Algorithm)。

在 1977 年,Robert S. Boyer (Stanford Research Institute) 和 J Strother Moore (Xerox Palo Alto Research Center) 共同发表了文章《A Fast String Searching Algorithm》,介绍了一种新的快速字符串匹配算法。这种算法在逻辑上相对于现有的算法有了显著的改进,它对要搜索的字符串进行倒序的字符比较,并且当字符比较不匹配时无需对整个模式串再进行搜索。

Boyer-Moore 算法的主要特点有:

  1. 对模式字符的比较顺序时从右向左;
  2. 预处理需要 O(m + σ) 的时间和空间复杂度;
  3. 匹配阶段需要 O(m × n) 的时间复杂度;
  4. 匹配阶段在最坏情况下需要 3n 次字符比较;
  5. 最优复杂度 O(n/m);

下面是几种常见的字符串匹配算法的性能比较。

在 Naive 算法中,对文本 T 和模式 P 字符串均未做预处理。而在 KMP 算法中则对模式 P 字符串进行了预处理操作,以预先计算模式串中各位置的最长相同前后缀长度的数组。Boyer–Moore 算法同样也是对模式 P 字符串进行预处理。

我们知道,在 Naive 算法中,如果发现模式 P 中的字符与文本 T 中的字符不匹配时,需要将文本 T 的比较位置向后滑动一位,模式 P 的比较位置归 0 并从头开始比较。而 KMP 算法则是根据预处理的结果进行判断以使模式 P 的比较位置可以向后滑动多个位置。Boyer–Moore 算法的预处理过程也是为了达到相同效果。

Boyer–Moore 算法在对模式 P 字符串进行预处理时,将采用两种不同的启发式方法。这两种启发式的预处理方法称为:

  1. 坏字符(Bad Character Heuristic):当文本 T 中的某个字符跟模式 P 的某个字符不匹配时,我们称文本 T 中的这个失配字符为坏字符。
  2. 好后缀(Good Suffix Heuristic):当文本 T 中的某个字符跟模式 P 的某个字符不匹配时,我们称文本 T 中的已经匹配的字符串为好后缀。

Boyer–Moore 算法在预处理时,将为两种不同的启发法结果创建不同的数组,分别称为 Bad-Character-Shift(or The Occurrence Shift)和 Good-Suffix-Shift(or Matching Shift)。当进行字符匹配时,如果发现模式 P 中的字符与文本 T 中的字符不匹配时,将比较两种不同启发法所建议的移动位移长度,选择最大的一个值来对模式 P 的比较位置进行滑动。

此外,Naive 算法KMP 算法对模式 P 的比较方向是从前向后比较,而 Boyer–Moore 算法的设计则是从后向前比较,即从尾部向头部方向进行比较。

下面,我们将以 J Strother Moore 提供的例子作为示例。

   Text T : HERE IS A SIMPLE EXAMPLE
Pattern P : EXAMPLE

首先将文本 T 与模式 P 头部对齐,并从尾部开始进行比较。(注1

这样如果尾部的字符不匹配,则前面的字符也就无需比较了,直接跳过。我们看到,"S" 与 "E" 不匹配,我们称文本 T 中的失配字符 "S" 为坏字符(Bad Character)

由于字符 "S" 在模式 "EXAMPLE" 中不存在,则可将搜索位置滑动到 "S" 的后面。

仍然从尾部开始比较,发现 "P" 与 "E" 不匹配,所以 "P" 是坏字符。但此时,"P" 包含在模式 "EXAMPLE" 之中。所以,将模式后移两位,使两个 "P" 对齐。

由此总结坏字符启发法的规则是:

模式后移位数 = 坏字符在模式中失配的位置 - 坏字符在模式中最后一次出现的位置

坏字符启发法规则中的特殊情况:

  1. 如果坏字符不存在于模式中,则最后一次出现的位置为 -1。
  2. 如果坏字符在模式中的位置位于失配位置的右侧,则此启发法不提供任何建议。

The bad character shift means to shift the pattern so that the text character of the mismatch is aligned to the last occurrence of that character in the initial part of the pattern (pattern minus last pattern character), if there is such an occurrence, or one position before the pattern if the mismatched character doesn't appear in the initial part of the pattern at all.

以上面示例中坏字符 "P" 为例,它的失配位置为 "E" 的位置 6 (位置从 0 开始),在模式中最后一次出现的位置是 4,则模式后移位数为 6 - 4 = 2 位。模式移动的结果就是使模式中最后出现的 "P" 与文本中的坏字符 "P" 进行对齐。

实际上,前面的坏字符 "S" 出现时,其失配位置为 6,最后一次出现位置为 -1,所以模式后移位数为 6 - (-1) = 7 位。也就是将模式整体移过坏字符。

我们继续上面的过程,仍然从尾部开始比较。

仍然从尾部开始比较,发现 "E" 与 "E" 匹配,则继续倒序比较。

发现 "L" 与 "L" 匹配,则继续倒序比较。

发现 "P" 与 "P" 匹配,则继续倒序比较。

发现 "M" 与 "M" 匹配,则继续倒序比较。

发现 "I" 与 "A" 不匹配,则 "I" 是坏字符。对于前面已经匹配的字符串 "MPLE"、"PLE"、"LE"、"E",我们称它们为好后缀(Good Suffix)

The good suffix shift, aligns the matched part of the text with the rightmost occurrence of that character sequence in the pattern that is preceded by a different character (including none, if the matched suffix is also a prefix of the pattern) than the matched suffix of the pattern - if there is such an occurrence.

而好后缀启发法的规则是:

模式后移位数 = 好后缀在模式中的当前位置 - 好后缀在模式中最右出现且前缀字符不同的位置

好后缀在模式中的当前位置以其最后一个字符为准。如果好后缀不存在于模式中,则最右出现的位置为 -1。

这样,我们先来找出好后缀在模式中上一次出现的位置。

  • "MPLE" : 未出现,最右出现的位置为 -1;
  • "PLE" : 未出现在头部,最右出现的位置为 -1;
  • "LE" : 未出现在头部,最右出现的位置为 -1;
  • "E" : 出现在头部,补充虚拟字符 'MPL'E,前缀字符为空,最右出现的位置为 0;

由于只有 "E" 在模式中出现,其当前位置为 6,上一次出现的位置为 0,则依据好后缀启发法规则,模式后移位数为 6 - 0 = 6 位。

而如果依据坏字符启发法规则,模式后移位数为 2 - (-1) = 3 位。

Boyer–Moore 算法的特点就在于此,选择上述两种启发法规则计算结果中最大的一个值来对模式 P 的比较位置进行滑动。这里将选择好后缀启发法的计算结果,即将模式向后移 6 位。

此时,仍然从尾部开始比较。

发现 "P" 与 "E" 不匹配,则 "P" 是坏字符,则模式后移位数为 6 - 4 = 2 位。

发现 "E" 与 "E" 匹配,则继续倒序比较,直到发现全部匹配,则匹配到的第一个完整的模式 P 被发现。

继续下去则是依据好后缀启示法规则计算好后缀 "E" 的后移位置为 6 - 0 = 6 位,然后继续倒序比较时发现已超出文本 T 的范围,搜索结束。

从上面的示例描述可以看出,Boyer–Moore 算法的精妙之处在于,其通过两种启示规则来计算后移位数,且其计算过程只与模式 P 有关,而与文本 T 无关。因此,在对模式 P 进行预处理时,可预先生成 "坏字符规则之向后位移表" 和 "好后缀规则之向后位移表",在具体匹配时仅需查表比较两者中最大的位移即可。

下面是 Boyer–Moore 算法的示例代码,使用 C# 语言实现。

 namespace StringMatching
{
class Program
{
static void Main(string[] args)
{
char[] text1 = "BBC ABCDAB ABCDABCDABDE".ToCharArray();
char[] pattern1 = "ABCDABD".ToCharArray(); int firstShift1;
bool isMatched1 = BoyerMooreStringMatcher.TryMatch(
text1, pattern1, out firstShift1);
Contract.Assert(isMatched1);
Contract.Assert(firstShift1 == ); char[] text2 = "ABABDAAAACAAAABCABAB".ToCharArray();
char[] pattern2 = "AAACAAAA".ToCharArray(); int firstShift2;
bool isMatched2 = BoyerMooreStringMatcher.TryMatch(
text2, pattern2, out firstShift2);
Contract.Assert(isMatched2);
Contract.Assert(firstShift2 == ); char[] text3 = "ABAAACAAAAAACAAAABCABAAAACAAAAFDLAAACAAAAAACAAAA"
.ToCharArray();
char[] pattern3 = "AAACAAAA".ToCharArray(); int[] shiftIndexes3 = BoyerMooreStringMatcher.MatchAll(text3, pattern3);
Contract.Assert(shiftIndexes3.Length == );
Contract.Assert(string.Join(",", shiftIndexes3) == "2,9,22,33,40"); char[] text4 = "GCATCGCAGAGAGTATACAGTACG".ToCharArray();
char[] pattern4 = "GCAGAGAG".ToCharArray(); int firstShift4;
bool isMatched4 = BoyerMooreStringMatcher.TryMatch(
text4, pattern4, out firstShift4);
Contract.Assert(isMatched4);
Contract.Assert(firstShift4 == ); char[] text5 = "HERE IS A SIMPLE EXAMPLE AND EXAMPLE OF BM.".ToCharArray();
char[] pattern5 = "EXAMPLE".ToCharArray(); int firstShift5;
bool isMatched5 = BoyerMooreStringMatcher.TryMatch(
text5, pattern5, out firstShift5);
Contract.Assert(isMatched5);
Contract.Assert(firstShift5 == );
int[] shiftIndexes5 = BoyerMooreStringMatcher.MatchAll(text5, pattern5);
Contract.Assert(shiftIndexes5.Length == );
Contract.Assert(string.Join(",", shiftIndexes5) == "17,29"); Console.WriteLine("Well done!");
Console.ReadKey();
}
} public class BoyerMooreStringMatcher
{
private static int AlphabetSize = ; private static int Max(int a, int b) { return (a > b) ? a : b; } static int[] PreprocessToBuildBadCharactorHeuristic(char[] pattern)
{
int m = pattern.Length;
int[] badCharactorShifts = new int[AlphabetSize]; for (int i = ; i < AlphabetSize; i++)
{
//badCharactorShifts[i] = -1;
badCharactorShifts[i] = m;
} // fill the actual value of last occurrence of a character
for (int i = ; i < m; i++)
{
//badCharactorShifts[(int)pattern[i]] = i;
badCharactorShifts[(int)pattern[i]] = m - - i;
} return badCharactorShifts;
} static int[] PreprocessToBuildGoodSuffixHeuristic(char[] pattern)
{
int m = pattern.Length;
int[] goodSuffixShifts = new int[m];
int[] suffixLengthArray = GetSuffixLengthArray(pattern); for (int i = ; i < m; ++i)
{
goodSuffixShifts[i] = m;
} int j = ;
for (int i = m - ; i >= -; --i)
{
if (i == - || suffixLengthArray[i] == i + )
{
for (; j < m - - i; ++j)
{
if (goodSuffixShifts[j] == m)
{
goodSuffixShifts[j] = m - - i;
}
}
}
} for (int i = ; i < m - ; ++i)
{
goodSuffixShifts[m - - suffixLengthArray[i]] = m - - i;
} return goodSuffixShifts;
} static int[] GetSuffixLengthArray(char[] pattern)
{
int m = pattern.Length;
int[] suffixLengthArray = new int[m]; int f = , g = , i = ; suffixLengthArray[m - ] = m; g = m - ;
for (i = m - ; i >= ; --i)
{
if (i > g && suffixLengthArray[i + m - - f] < i - g)
{
suffixLengthArray[i] = suffixLengthArray[i + m - - f];
}
else
{
if (i < g)
{
g = i;
}
f = i; // find different preceded character suffix
while (g >= && pattern[g] == pattern[g + m - - f])
{
--g;
}
suffixLengthArray[i] = f - g;
}
} return suffixLengthArray;
} public static bool TryMatch(char[] text, char[] pattern, out int firstShift)
{
firstShift = -;
int n = text.Length;
int m = pattern.Length;
int s = ; // s is shift of the pattern with respect to text
int j = ; // fill the bad character and good suffix array by preprocessing
int[] badCharShifts = PreprocessToBuildBadCharactorHeuristic(pattern);
int[] goodSuffixShifts = PreprocessToBuildGoodSuffixHeuristic(pattern); while (s <= (n - m))
{
// starts matching from the last character of the pattern
j = m - ; // keep reducing index j of pattern while characters of
// pattern and text are matching at this shift s
while (j >= && pattern[j] == text[s + j])
{
j--;
} // if the pattern is present at current shift, then index j
// will become -1 after the above loop
if (j < )
{
firstShift = s;
return true;
}
else
{
// shift the pattern so that the bad character in text
// aligns with the last occurrence of it in pattern. the
// max function is used to make sure that we get a positive
// shift. We may get a negative shift if the last occurrence
// of bad character in pattern is on the right side of the
// current character.
//s += Max(1, j - badCharShifts[(int)text[s + j]]);
// now, compare bad char shift and good suffix shift to find best
s += Max(goodSuffixShifts[j], badCharShifts[(int)text[s + j]] - (m - ) + j);
}
} return false;
} public static int[] MatchAll(char[] text, char[] pattern)
{
int n = text.Length;
int m = pattern.Length;
int s = ; // s is shift of the pattern with respect to text
int j = ;
int[] shiftIndexes = new int[n - m + ];
int c = ; // fill the bad character and good suffix array by preprocessing
int[] badCharShifts = PreprocessToBuildBadCharactorHeuristic(pattern);
int[] goodSuffixShifts = PreprocessToBuildGoodSuffixHeuristic(pattern); while (s <= (n - m))
{
// starts matching from the last character of the pattern
j = m - ; // keep reducing index j of pattern while characters of
// pattern and text are matching at this shift s
while (j >= && pattern[j] == text[s + j])
{
j--;
} // if the pattern is present at current shift, then index j
// will become -1 after the above loop
if (j < )
{
shiftIndexes[c] = s;
c++; // shift the pattern so that the next character in text
// aligns with the last occurrence of it in pattern.
// the condition s+m < n is necessary for the case when
// pattern occurs at the end of text
//s += (s + m < n) ? m - badCharShifts[(int)text[s + m]] : 1;
s += goodSuffixShifts[];
}
else
{
// shift the pattern so that the bad character in text
// aligns with the last occurrence of it in pattern. the
// max function is used to make sure that we get a positive
// shift. We may get a negative shift if the last occurrence
// of bad character in pattern is on the right side of the
// current character.
//s += Max(1, j - badCharShifts[(int)text[s + j]]);
// now, compare bad char shift and good suffix shift to find best
s += Max(goodSuffixShifts[j], badCharShifts[(int)text[s + j]] - (m - ) + j);
}
} int[] shifts = new int[c];
for (int y = ; y < c; y++)
{
shifts[y] = shiftIndexes[y];
} return shifts;
}
}
}

参考资料

注1:文章中部分示例图片来自阮一峰的博客文章《字符串匹配的Boyer-Moore算法》,这篇文章已经写的足够透彻了,但是我还是希望通过自己叙述的理解来加深记忆。

注2:本文《Boyer-Moore 字符串匹配算法》由 Dennis Gao 发表自博客园博客,任何未经作者本人允许的人为或爬虫转载均为耍流氓。

Boyer-Moore 字符串匹配算法的更多相关文章

  1. 字符串匹配算法之BM算法

    BM算法,全称是Boyer-Moore算法,1977年,德克萨斯大学的Robert S. Boyer教授和J Strother Moore教授发明了一种新的字符串匹配算法. BM算法定义了两个规则: ...

  2. 图解BM(Boyer-Moore)字符串匹配算法+代码实现

    简介 本篇文章主要分为两个大的部分,第一部分通过图解的方式讲解BM算法,第二部分则代码实现一个简易的BM算法. 基本概念 bm是一个字符串匹配算法,有实验统计,该算法是著名kmp算法性能的3-4倍,其 ...

  3. 字符串匹配算法 - KMP

    前几日在微博上看到一则微博是说面试的时候让面试者写一个很简单的字符串匹配都写不出来,于是我就自己去试了一把.结果写出来的是一个最简单粗暴的算法.这里重新学习了一下几个经典的字符串匹配算法,写篇文章以巩 ...

  4. KMP单模快速字符串匹配算法

    KMP算法是由Knuth,Morris,Pratt共同提出的算法,专门用来解决模式串的匹配,无论目标序列和模式串是什么样子的,都可以在线性时间内完成,而且也不会发生退化,是一个非常优秀的算法,时间复杂 ...

  5. 字符串匹配算法之BF(Brute-Force)算法

    BF(Brute-Force)算法 蛮力搜索,比较简单的一种字符串匹配算法,在处理简单的数据时候就可以用这种算法,完全匹配,就是速度慢啊. 基本思想 从目标串s 的第一个字符起和模式串t的第一个字符进 ...

  6. 【原创】通俗易懂的讲解KMP算法(字符串匹配算法)及代码实现

    一.本文简介 本文的目的是简单明了的讲解KMP算法的思想及实现过程. 网上的文章的确有些杂乱,有的过浅,有的太深,希望本文对初学者是非常友好的. 其实KMP算法有一些改良版,这些是在理解KMP核心思想 ...

  7. 字符串匹配算法——KMP算法学习

    KMP算法是用来解决字符串的匹配问题的,即在字符串S中寻找字符串P.形式定义:假设存在长度为n的字符数组S[0...n-1],长度为m的字符数组P[0...m-1],是否存在i,使得SiSi+1... ...

  8. 4种字符串匹配算法:KMP(下)

    回顾:4种字符串匹配算法:BS朴素 Rabin-karp(上) 4种字符串匹配算法:有限自动机(中) 1.图解 KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R ...

  9. 4种字符串匹配算法:BS朴素 Rabin-karp(上)

    字符串的匹配的算法一直都是比较基础的算法,我们本科数据结构就学过了严蔚敏的KMP算法.KMP算法应该是最高效的一种算法,但是确实稍微有点难理解.所以打算,开这个博客,一步步的介绍4种匹配的算法.也是& ...

随机推荐

  1. Futoshiki求解

    Futoshiki求解 Futoshiki是对于一个n的方阵,需要满足如下条件: ·每一行和每一列的元素都不能重复,即每一行和每一列1到n,n个数字都出现,且只出现一次. ·同一行或同一列中相邻两个元 ...

  2. c#输出、输入

    //输出 Console.WriteLine("这是一行文字");  自动回车的. Console.Write("Hello world");  不带回车的. ...

  3. CMake 使用方法(转)

    CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程).他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的 ...

  4. [mk] 喝一杯咖啡, 写一写 Makefile

    Makefile 是 Linux 下组织程序的一个工具,它的命令是 make. (首字母M/m都可以) [Makefile] Makefile 编写的主旋律: target: [dependency] ...

  5. 说说Statement、PreparedStatement和CallableStatement的异同(转)

    1.Statement.PreparedStatement和CallableStatement都是接口(interface). 2.Statement继承自Wrapper.PreparedStatem ...

  6. Q_OBJECT

    所有QObject的派生类在官方文档中都推荐在头文件中放置宏Q_OBJECT,那么该宏到底为我们做了哪些工作?在qobjectdef.h中有下面的代码: #define Q_OBJECT \ publ ...

  7. JSTL和EL表达式多重if问题

    俾人以前在写一个查询功能时,由于结果状态分好几种,于是页面就用<c:if></c:if>写了一大堆来判断,后来上网查了下资料,发现有个语法类似于多重if,挺方便的,语法是 &l ...

  8. FibonacciSequence

    import java.util.Scanner; public class Fibonacci { public static void main(String[] args) { int n; f ...

  9. CSS clear清除浮动

    1.CSS中的clear有四个参数: none:允许两边都可以浮动. left:不允许左边有浮动. right:不允许右边有浮动. both(默认):不允许有浮动. 2.一开始在CSS中clear浮动 ...

  10. 【安装mysql数据库】

    方法/步骤   请注意上图中选择Custom选项,这样才能修改安装目录.   请注意为了数据安全,不要把mysql安装在系统盘,如C:盘. 可以在其他盘符下,新建两个文件夹,一个存储mysql的文件, ...