Boyer-Moore 字符串匹配算法
字符串匹配问题的形式定义:
- 文本(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 算法的主要特点有:
- 对模式字符的比较顺序时从右向左;
- 预处理需要 O(m + σ) 的时间和空间复杂度;
- 匹配阶段需要 O(m × n) 的时间复杂度;
- 匹配阶段在最坏情况下需要 3n 次字符比较;
- 最优复杂度 O(n/m);
下面是几种常见的字符串匹配算法的性能比较。
在 Naive 算法中,对文本 T 和模式 P 字符串均未做预处理。而在 KMP 算法中则对模式 P 字符串进行了预处理操作,以预先计算模式串中各位置的最长相同前后缀长度的数组。Boyer–Moore 算法同样也是对模式 P 字符串进行预处理。
我们知道,在 Naive 算法中,如果发现模式 P 中的字符与文本 T 中的字符不匹配时,需要将文本 T 的比较位置向后滑动一位,模式 P 的比较位置归 0 并从头开始比较。而 KMP 算法则是根据预处理的结果进行判断以使模式 P 的比较位置可以向后滑动多个位置。Boyer–Moore 算法的预处理过程也是为了达到相同效果。
Boyer–Moore 算法在对模式 P 字符串进行预处理时,将采用两种不同的启发式方法。这两种启发式的预处理方法称为:
- 坏字符(Bad Character Heuristic):当文本 T 中的某个字符跟模式 P 的某个字符不匹配时,我们称文本 T 中的这个失配字符为坏字符。
- 好后缀(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。
- 如果坏字符在模式中的位置位于失配位置的右侧,则此启发法不提供任何建议。
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;
}
}
}
参考资料
- Fast String Searching Algorithm Example
- Boyer–Moore string search algorithm
- Pattern Searching | Set 7 (Boyer Moore Algorithm – Bad Character Heuristic)
- The Boyer-Moore-Horspool Algorithm
- 字符串匹配的Boyer-Moore算法
- Boyer-Moore algorithm
- What are the shift rules for Boyer–Moore string search algorithm?
- CS 312 Lecture 27 - String matching
- Boyer-Moore good-suffix heuristics
- Boyer Moore Exact Pattern Matching Algorithms
注1:文章中部分示例图片来自阮一峰的博客文章《字符串匹配的Boyer-Moore算法》,这篇文章已经写的足够透彻了,但是我还是希望通过自己叙述的理解来加深记忆。
注2:本文《Boyer-Moore 字符串匹配算法》由 Dennis Gao 发表自博客园博客,任何未经作者本人允许的人为或爬虫转载均为耍流氓。
Boyer-Moore 字符串匹配算法的更多相关文章
- 字符串匹配算法之BM算法
BM算法,全称是Boyer-Moore算法,1977年,德克萨斯大学的Robert S. Boyer教授和J Strother Moore教授发明了一种新的字符串匹配算法. BM算法定义了两个规则: ...
- 图解BM(Boyer-Moore)字符串匹配算法+代码实现
简介 本篇文章主要分为两个大的部分,第一部分通过图解的方式讲解BM算法,第二部分则代码实现一个简易的BM算法. 基本概念 bm是一个字符串匹配算法,有实验统计,该算法是著名kmp算法性能的3-4倍,其 ...
- 字符串匹配算法 - KMP
前几日在微博上看到一则微博是说面试的时候让面试者写一个很简单的字符串匹配都写不出来,于是我就自己去试了一把.结果写出来的是一个最简单粗暴的算法.这里重新学习了一下几个经典的字符串匹配算法,写篇文章以巩 ...
- KMP单模快速字符串匹配算法
KMP算法是由Knuth,Morris,Pratt共同提出的算法,专门用来解决模式串的匹配,无论目标序列和模式串是什么样子的,都可以在线性时间内完成,而且也不会发生退化,是一个非常优秀的算法,时间复杂 ...
- 字符串匹配算法之BF(Brute-Force)算法
BF(Brute-Force)算法 蛮力搜索,比较简单的一种字符串匹配算法,在处理简单的数据时候就可以用这种算法,完全匹配,就是速度慢啊. 基本思想 从目标串s 的第一个字符起和模式串t的第一个字符进 ...
- 【原创】通俗易懂的讲解KMP算法(字符串匹配算法)及代码实现
一.本文简介 本文的目的是简单明了的讲解KMP算法的思想及实现过程. 网上的文章的确有些杂乱,有的过浅,有的太深,希望本文对初学者是非常友好的. 其实KMP算法有一些改良版,这些是在理解KMP核心思想 ...
- 字符串匹配算法——KMP算法学习
KMP算法是用来解决字符串的匹配问题的,即在字符串S中寻找字符串P.形式定义:假设存在长度为n的字符数组S[0...n-1],长度为m的字符数组P[0...m-1],是否存在i,使得SiSi+1... ...
- 4种字符串匹配算法:KMP(下)
回顾:4种字符串匹配算法:BS朴素 Rabin-karp(上) 4种字符串匹配算法:有限自动机(中) 1.图解 KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R ...
- 4种字符串匹配算法:BS朴素 Rabin-karp(上)
字符串的匹配的算法一直都是比较基础的算法,我们本科数据结构就学过了严蔚敏的KMP算法.KMP算法应该是最高效的一种算法,但是确实稍微有点难理解.所以打算,开这个博客,一步步的介绍4种匹配的算法.也是& ...
随机推荐
- 近期微博吐槽言论存档,涉及“性能优化”、C++陋习等
写C++程序的几个陋习:class 名以大写 C 开头,例如 CDate:成员变量以 m_ 开头:变量采用匈牙利命名法:不知道何时禁用 copy-ctor/assign operator.前三个可能是 ...
- Golang 文件服务器小结
花了一个星期学习文件服务器,老是在一些地方搞混,整理一下所学的,清晰了不少. 学Go半个月,还有很多不懂的地方,有理解错误的,还望高手指出. 注:以下代码中,w为http.ResponseWriter ...
- 大漠绑定测试工具-VB6
获取更新开始|版本:3.1652版 2016年12月27日|更新内容:1.取消自动更新错误的提示.\n\n友情提示:如网盘失效,请加QQ群(568073679)下载最新版|下载地址:http://ww ...
- spring 事务:注解方式
(1) .<context:component-scan base-package="*.*" /> 该配置隐式注册了多个对注解进行解析的处理器,如: Autowire ...
- 无法删除服务器 'old_server_name',因为该服务器用作复制过程中的发布服务器。 (Microsoft SQL Server,错误: 20582)
无法删除服务器 'old_server_name',因为该服务器用作复制过程中的发布服务器. (Microsoft SQL Server,错误: 20582) 2013-01-05 15:02 478 ...
- Windows下的UDP爆了10054--远程主机强迫关闭了一个现有的连接
原文地址:http://www.cnblogs.com/pasoraku/p/5612105.html 故事是这样的. 前几天在网上逛,看到了一个漂亮的坦克模型. 我觉得这个坦克可以做一个游戏,那需要 ...
- CSS布局技巧 -- sticky属性
在一些很长的表格中,往往需要使用表头悬浮的设计以方便用户使用,例如H5电商页面通过下滑展示大量商品列表时,顶部的导航栏需要在离开屏幕时,需要固定在屏幕顶部以方便用户筛选类别.这种效果一直以来需要通过J ...
- 国内及Github优秀开发人员列表
自从入了Android软件开发的行道,解决问题和学习过程中免不了会参考别人的思路,浏览博文和门户网站成了最大的入口.下面这些列表取名为:国内及Github优秀开发人员列表,就是浏览后的成果. 虽然下述 ...
- $(function(){})、$(document).ready(function(){})....../ ready和onload的区别
1.window.onload 当一个文档完全下载到浏览器中时,会触发 window.onload 事件. 这意味着页面上的全部元素对 javascript 而言都是可以访问的,这种情况对编写功能性的 ...
- Coursera Robotics系列课心得
Robotics Perception Professor Kostas and Jianbo Shi week 1: camera model 凸透镜成像原理:凸透镜焦点与焦距是固定的,这是物理性质 ...