文章目录
1 串匹配概述
字符串匹配有多种形式,包括模式检测( pattern detection),模式定位(pattern location),模式计数(pattern counting),模式枚举(pattern enumration)。
2 蛮力算法
蛮力算法是最直接最直觉的方法,可以作为改进的基础。
2.1 蛮力算法版本A
//brute-force-A.h
#include <cstring>
int matchA( char* P, char* T ){
//串匹配算法(Brute-force-1)
size_t n = strlen( T ), i = 0;
size_t m = strlen( P ), j = 0;
while ( j < m && i < n )
if( T[i] == P[j] )//匹配则转到下一个字符
{
++i; ++j; }
else{
//不匹配则文本串回退,模式串复位
i -= j - 1;
j = 0;
}
return i - j;
}
2.2 蛮力算法版本B
//brute-force-B.h
#include <cstring>
int matchB( char* P, char* T ){
//串匹配算法(Brute-force-2)
size_t n = strlen( T ), i = 0;
size_t m = strlen( P ), j ;
for( i = 0; i < n - m + 1; ++i ){
//文本串从第i个字符开始逐个比对
for( j = 0; j < m; ++j){
if( T[i + j] != P[j] ) break;//失配则右移再做一轮比对
}
if( j >= m ) break; //找到匹配子串
}
return i;
}
2.3 蛮力算法测试
蛮力算法的测试程序如下,可见匹配成功时,版本A与版本B都会返回模式串在文本串中的位置。串匹配失败时,版本1返回大于n-m,版本2返回n-m+1。
/*
* test program on string matching
* author@Ripples
* 20200807
*/
#include "brute-force-A.h"
#include "brute-force-B.h"
#include <iostream>
using namespace std;
int main(){
//初始化模式串与文本串
char P[] = "structure";
char Y[] = "alo";
char T[] =