kmp算法[英文详解](转)

kmp算法[英文详解](转)

ID:26251191

大小:58.50 KB

页数:16页

时间:2018-11-25

kmp算法[英文详解](转)_第1页
kmp算法[英文详解](转)_第2页
kmp算法[英文详解](转)_第3页
kmp算法[英文详解](转)_第4页
kmp算法[英文详解](转)_第5页
资源描述:

《kmp算法[英文详解](转)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库

1、Knuth-Morris-PrattstringmatchingTheproblem:givena(short)patternanda(long)text,bothstrings,determinewhetherthepatternappearssomewhereinthetext. Lasttime wesawhowtodothiswithfiniteautomata.Thistimewe'llgothroughthe Knuth-Morris-Pratt (KMP)algorithm,whichcanbethoughtofasaneffici

2、entwaytobuildtheseautomata.Ialsohavesome workingC++sourcecodewhichmighthelpyouunderstandthealgorithmbetter.Firstlet'slookatanaivesolution.supposethetextisinanarray:charT[n]andthepatternisinanotherarray:charP[m].Onesimplemethodisjusttotryeachpossiblepositionthepatterncouldappe

3、arinthetext.Naivestringmatching:for(i=0;T[i]!='';i++){for(j=0;T[i+j]!=''&&P[j]!=''&&T[i+j]==P[j];j++);if(P[j]=='')foundamatch}Therearetwonestedloops;theinneronetakesO(m)iterationsandtheouteronetakesO(n)iterationssothetotaltimeistheproduct,O(mn).Thisisslow;we'dliketosp

4、eeditup.Inpracticethisworksprettywell--notusuallyasbadasthisO(mn)worstcaseanalysis.Thisisbecausetheinnerloopusuallyfindsamismatchquicklyandmoveontothenextpositionwithoutgoingthroughallmsteps.ButthismethodstillcantakeO(mn)forsomeinputs.Inonebadexample,allcharactersinT[]are"a"s

5、,andP[]isall"a"'sexceptforone"b"attheend.Thenittakesmcomparisonseachtimetodiscoverthatyoudon'thaveamatch,somnoverall.Here'samoretypicalexample.Eachrowrepresentsaniterationoftheouterloop,witheachcharacterintherowrepresentingtheresultofacomparison(Xifthecomparisonwasunequal).Su

6、pposewe'relookingforpattern"nano"intext"banananobano".01234567891011T:banananobanoi=0:Xi=1:Xi=2:nanXi=3:Xi=4:nanoi=5:Xi=6:nXi=7:Xi=8:Xi=9:nXi=10:XSomeofthesecomparisonsarewastedwork!Forinstance,afteriterationi=2,weknowfromthecomparisonswe'vedonethatT[3]="a",sothereisnopointco

7、mparingitto"n"initerationi=3.AndwealsoknowthatT[4]="n",sothereisnopointmakingthesamecomparisoniniterationi=4.SkippingouteriterationsTheKnuth-Morris-Prattideais,inthissortofsituation,afteryou'veinvestedalotofworkmakingcomparisonsintheinnerloopofthecode,youknowalotaboutwhat'sin

8、thetext.Specifically,ifyou'vefoundapartialmatchofjcharactersstarting

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。