KMP(字符串匹配)算法
2013-11-18 10:35
405 查看
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } //模式数组 arrNext : array of Integer; //主串数组 Schars : array of AnsiChar; //字串数组 Dchars : array of AnsiChar; //获取模式数组 procedure GetNext; //查找匹配 function KPM(sPos:Integer):integer; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} { TForm1 } procedure TForm1.GetNext; var len,m,n:Integer; begin m := 0; n := -1; len := Length(Dchars); SetLength(arrNext,len); arrNext[0] := -1; while (m+1)<= len do begin if (n = -1) or (Dchars[m] = Dchars ) then begin Inc(m); Inc(n); if (Dchars[m] <> Dchars ) then arrNext[m] := n else arrNext[m] := arrNext ; end else begin n := arrNext ; end; end; end; function TForm1.KPM(sPos:Integer): integer; var i,j:Integer; begin Result := 0; i := sPos; j := 0; while (i < Length(Schars)) and (j < Length(Dchars)) do begin if (Schars[i] = Dchars[j]) then begin Inc(i); Inc(j); end else begin Result := Result + j - arrNext[j]; if arrNext[j] <> -1 then begin j := arrNext[j]; end else begin j := 0; Inc(i); end; end; end; if j <> Length(Dchars) then Result := -1; end; procedure TForm1.Button1Click(Sender: TObject); var s,d:string; index : Integer; begin s := '中华人民共和国'; d := '人民'; index := -1; SetLength(Schars,Length(s)); SetLength(Dchars,Length(d)); Move(s[1],Schars[0],Length(s)); Move(d[1],Dchars[0],Length(d)); GetNext; index := KPM(0); if index = -1 then ShowMessage('没有找到匹配!') else ShowMessage('从第'+IntToStr(index+1)+'个字符开始匹配'); end; end.
View Code
相关文章推荐
- KMP 字符串匹配算法
- KMP字符串匹配算法——用最容易理解的方式描述
- 字符串匹配算法:KMP
- ACM 算法 KMP 字符串匹配
- 字符串匹配算法之KMP
- 【字符串匹配】——KMP(看毛片算法)——深入讲解next数组的求解
- 字符串匹配算法---Brute force、KMP、Sunday
- 字符串匹配算法之KMP
- 算法学习之字符串匹配 KMP 算法(一)(原理介绍)
- Java实现 字符串匹配 KMP 算法
- 字符串匹配算法--KMP
- KMP字符串匹配算法 通俗理解
- 字符串匹配算法之KMP
- 【基本算法】 KMP文本串模式串的字符串匹配算法
- 数据结构与算法之KMP 字符串匹配
- KMP字符串匹配算法模板代码
- Kmp字符串匹配算法改进版
- 算法|KMP:字符串匹配(人话版)
- BM和KMP字符串匹配算法学习
- 字符串匹配算法之KMP&Boyer-Moore