一种基于有序二叉树的多模式匹配算法

一种基于有序二叉树的多模式匹配算法
一种基于有序二叉树的多模式匹配算法

Recived date:2002-09-19 基金项目:信息产业部中长期发展项目:2004-研1-B-034 作者简介:Liu Gong-s hen ,Ph.D,His research inter-es ts in clu de intelligent process ing of Intern et inform ation and anti -virus technology .E _m ail :lgsh en @s jtu .edu .cn ;

Multiple Pattern Matching Algorithm Based

on Sequential Binary Tree

1

LIU Gong -shen 1,LI Ning

2

1(

S chool of Inf ormation S ecurity Eng ineer ing ,S hang hai Jiaotong Univ ersity ,Shang hai 200030,China )

2

(Dep ar tment of C omp uter S cience ,Univ ersity of M anche ster M ancheste r ,Eng land )

Abstract :By ana ly zing the tr aditio na l multiple patt ern matching alg or ithm based o n tr ee str ucture,a new alg or ithm is

pr o po sed by substituting sequential binar y t ree for tr ee.T he a lg or ithm is suitable fo r the applicatio n w hich requir es pr epro cessing the pa tterns dynamically.It is pro ved by ex periment t ha t t he algo rithm has thr ee feat ur es:Its construc-tio n pr ocess is quick.Its co st o f memo ry is small.At the same t ime,it s searching pr ocess is as quick as t he tr aditio nal algo rit hm.

Key words :multiple patter n ma tching ;finite state auto mata;sequent ial binary tree

一种基于有序二叉树的多模式匹配算法

刘功申1,李 宁2

1(

上海交通大学信息安全学院,上海200030)

2(

曼彻斯特大学计算机系,英国)

摘 要:传统的多模式匹配算法是用树型结构的有限自动机实现的,它具有很多缺点.本文提出的多模式匹配算法是基于有序二叉树的多模式匹配算法.实验证明,本文算法不但具有和传统算法相当的查找速度,而且构造速度快、内存耗费少.因此,本文提出的算法特别适用于要求动态构造自动机的情况.

关键词:多模式匹配;D FSA ;有序二叉树

中图分类号:T P 301 文献标识码:A 文章编号:1000-1220(2004)07-1387-06

1 Introduction

Sear ching user-specified patter ns in a t ext file is a com-mon r equir ement in infor mation ret riev al and tex t editing ap-plications.N ow ,deter ministic finite state auto mata (DF SA )is the mo st co mmon method in so lv ing patter n match pr ob-lem [1,2].Befor e sear ching pro cess,the DF SA algo r ithm must prepro cess the patt ern set and co nst ruct an auto maton based on tr ee str uctur e.T hen,the o ccur rences of ever y patter n can be found by scanning the tex t file just once .So ,I ts tim e complex ity is O (n ).Jang -Jong F an and K eh-Yih Su pr oposed

a new algo r ithm by combining D FSA alg or ithm with Boy er -M o or e alg or ithm [3].T he alg or ithm o f Ja ng -Jong Fan and

K eh -Y ih Su do esn ?t need to inspect ever y chara ct er o f the tex t file,w hich is mo re efficient than D FSA algo rithm.

In pr act ical applications ,there are some new require-ments to be em phasized gr adually,such as,the requir ement of changing the pa tter n set that is to be sear ched dy na mically (i.e.the implement of t he function o f searching and replac-ing in t ext edit ing applica tio n )and the r equir ement of sav ing memo ry (i.e.implementing t he alg or ithm in PDA or embed-ded softw ar e ).A t the same time ,the searching efficiency

can ?t decrease .T he tr aditio na l alg or it hm based on t ree do esn ?t sat isfy these r equir ements,because its co nstr uct ion pr ocess is slo w and its cost o f memor y is excessive .

T he concept ion of sequential binar y tree (see definit ion 4in details )is pr o po sed or ig inally in this paper .A new mult i-ple pat tern matching alg or ithm---a multiple patter n matching

alg or ithm based on sequential binar y tr ee (in sho rt SM A al-g or it hm )is implemented by substituting sequential binar y tree for tr ee .T her e ar e many adv antages o f SM A a lg or ithm which ar e pr ov ed by our exper iment,such as quick construc-t ion ,the conv enience of adding o r deleting patter ns dy na mi-cally ,no requir ement s o f goto table,f ailur e table and outp ut table w hich ar e r equir ed in tr aditio na l algo rithm a nd high sear ching efficiency as tradit ional algo rit hm.

In the next sectio n ,we w ill descr ibe the disadv antages of tr aditional multiple pat tern matching algo r ithm.T he ad-v antag es o f SM A alg or it hm a re intr oduced in sectio n 3.In section 4and 5,the constr uction and searching alg or ithms of sequent ial bina ry tree a re g iv en .Sectio n 6and 7ar e algo -r it hm analysis and co nt rast ex per iments.Finally,section 8co ncludes this paper w ith so me remar ks .

 第25卷第7期 2004年7月

小型微型计算机系统M IN I -M ICR O SY ST EM S V ol .25N o .7 July 2004

2 Shortcomings of traditional algorithm

T he tr aditio nal alg or it hm is descr ibed in pa per [1]in de-tail.In or der to describe ea sily ,a sample is g iven.T he pat-tern set is {he ,hers ,his ,ho ur ,she ,o ur }.T he co rr espo nd-ing t ree is show n as fig ur e

1.

F ig.1 A uto mata based o n tree

If a no de of a tree has n sub-tr ees,the node must have n

pointer s w hich po int to its childr en r espectively .During the construction pro cess of tr ee,it is no t decided in advance ho w many sub -t rees a node has .T her e ar e only t wo met ho ds to

handle it.T he fir st method is to re-a llocate the memor y o f

parent node w hen a sub-tr ee is added each time.T he second method is that the memor y o f m (m is the maximum number of sub-t rees of ev ery node )pointer is allo cat ed to ev er y

node ,w hich co sts the memor y v ery much

.

F ig.2 A uto mata based o n sequential binar y t ree T he goto ta ble,f ailur e table and outp ut table o f t radi-tio na l algo rit hm also need larg e mem or y .T heir size is pr o-po rt ional to the number of nodes of the tr ee in direct.Dur ing the course o f co nstr uctio n o f t raditional alg o-rithm,the patter ns are not so rt ed in the o rder o f dictionar y.T hat is t o say,if the pat terns of g iven patter n set a re not sor ted in dictionar y or der ,the tree is no t an or der ed t ree .T he sear ching r ate must be slo w if the tree is not or dered [5]

.In the giv en sa mple ,t he patt erns "she "and "o ur "ar e not in the dict ionar y o rder.

3 Advantages of SMA algorithm

In or der to o ver co me the shor tcom ings o f tr aditio nal al-g or it hm ,SM A alg or ithm implements multiple pat tern matching pro cess by using sequential binar y t ree instead of tree .If ther e is a patter n set {he ,hers ,his ,ho ur ,she ,our },the sequential binary t ree of the patter n set is show n as Fig ure 2.

T he advantag es o f the SM A algo rithm:?Impro ve the constr uction r ate

Because the binar y tree has only tw o sub -tr ees (left and

right sub-t rees ),we do n ?t need to g uess ho w many sub-trees a no de has .So ,we can a void o f co st ing memo ry exces-sively o r allo cating and r eleasing the memor y fr equently.

?Impro ve the sear ching efficiency

Because t he sequentia l binar y tr ee em bo dies t he dictio -nar y o rder o f all patt erns,the tr ansitio n r ate of state is mo re quick (see Sectio n 6.2).

?Add and delete patter n conveniently Because it is co nvenient to a dd o r delet e no de fr om bina-r y t ree,the SM A alg or it hm can add o r delete patter n co nv e-niently .

?Do n ?t need goto table,f ailur e table and outp ut table.T he SM A algo rithm uses point er inst ead of goto ,f ailur e and outp ut table ,so it can sav e the memor y .

4 Construction of sequential binary tree

4.1 Correlation def inition

T he sequential binary t ree sho w n in Fig ure 2is con-str ucted fr om patt ern set {he,her s,his,ho ur,she,our }.If we v isit the sequential binar y t ree accor ding to a special rule ,a patter n can be gained dur ing the visiting pr ocess fr om ro ot no de to a leaf no de.T he v isiting rule is descr ibed as fol-low s :

4.1.1 D efinition 1Visiting Rule:A stack s is used to save pat terns .A po inter p is used to keep t rack the no de .W hen p points to the r ight sub-tr ee of cur rent node and e is a edge bet ween curr ent node and its r ig ht sub-tr ee,t he item at the

top of st ack s is r emo ved then the chara ct er of edg e e is a dded to st ack s .When p po ints t o the left sub-tr ee of cur rent

no de ,the character of edg e e is added to stack s directly .Re-peat abov e pr ocess until p po ints t o the leaf node.N ow ,a pat tern is consisted of all items of t he st ack s .Fo r example ,the visiting pr ocess of patt ern "our "is described as fo llow s:(the sequential bina ry tr ee of patt ern set is sho wn as F ig ure 2)

Step 1:s =5;p =0;(r oot no de )

1388

小 型 微 型 计 算 机 系 统 2004年

Step 2:s ={h };p =1;(left child )

Step 3:character "h"is remo ved,"o "is added,s ={o };p =10;(r ig ht child )

Step 4:char acter "u"is added,s ={o ,u};p =11;(left child)

Step 5:char acter "r "is a dded,s ={o ,u,r };p =12;(left child)

T he pr ocess is ended.T he patt ern "our "is consisted o f all char act ers of stack s .

4.1.2 Definitio n 2Stat e depth

T he state depth o f a node is differ ent fr om the node depth o f bina ry tree .T he state depth reflects the position o f a chara ct er in the pa tter n.T he st ate dept h of a node can be defined in a r ecur siv e way as follo w s

:

F ig.3 State dept h o f nodes and their pat ernit y T he state depth of r oo t is 0;

If ther e is a node w ho se state depth is h ,the stat e dept h of its left child no de is h +1,the state depth of it s r ig ht child node is h

.

F ig.4 A sequentia l binar y tr ee w ith failure po inter T he stat e depth o f all nodes can be figur ed out analog i-ca lly.

A cco rding to the definition ,we can figur e o ut the stat e depth of ever y node o f the sample given in t his paper.T he state depth o f ev er y node is sho wn in F igur e 3.T he A r abic number in cir cle is the state depth of curr ent node.

4.1.3 Definitio n 3Fat her and child st ate node

Let the no de l be the left child no de o f no de f ,the no de set R={r ?r is the no de in right child tree o f l and its state depth is equiv alent to that o f l }.T he no de f is t he father st ate no de of ever y node o f R and node l .Ev ery no de of R and node l is the child stat e node of node f .T he pa ternit y of st ate no de is sho wn in F ig ur e 3.T he dot lines w ith arr ow -head descr ibe the r elationship of ev ery state no de.T he no de of arr ow head is the father stat e node o f the no de of bott om and t he node o f bo tto m is the child stat e o f the node o f ar -r ow head.

4.1.4 Definitio n 4Sequential binary tr ee

If w e trav erse the binar y tr ee on N L R mode,a ser ies of pat terns can be at tained by applying the v isit ing rule o f this paper.If these pat terns ar e sor ted in t heir dict ionar y or der ,the bina ry tree is a sequential binary tr ee.T he binary tree in Fig ure 2is a sequential binary tr ee .

4.2 The construction of sequential binary tree

If a patt ern set in w hich pat terns ar e no t in dict ionar y or der is given,the fir st ta sk is to construct a sequential bina-r y t ree.D ur ing the co urse of co nstr uctio n,there ar e some tasks t o do :co nstr uct ing the sequent ial binar y tr ee ,mar king the output node,defining the father state node of ever y no de ,and so rting patter ns in or der to increase the sear ching efficiency.

T he da ta structure o f tr ee no de :

S tructure Nod e { Node *Lchild ; C har Lchar; Node *Rchild; C har Rchar;

Node*fathers tate; Node*fails tate; Boolean output ;};

Algorithm 1.The const ruction of sequential binary tree Input :pat tern set

Output :T he sequent ial binar y tr ee ,output node and father st ate node po inter

Begin

for each pattern do { p =root;i=0;

w hile((p =goto (p ,p attern [i ]))!=NU LL )i++; in ser t pattern [i:strlen(pattern)]in pointer p ; }E nd .

Definition 5Function goto (state ,character )

Accor ding t o the visiting r ule ,w e visit sequent ial binar y tree fr om stat e no de p to o ne of child sta te nodes o f state no de p .If w e arr iv e at child state node c a nd a chara ct er char is in st ack ,then g oto (p ,char )=c ,else go to (p ,char )=NU LL.T he algo rithm describes as fo llow s:

1389

7期 刘功申等:一种基于有序二叉树的多模式匹配算法

Algorithm2.goto(p,char)

Input:pointer p,character char

Output:child state node or N U L L

Begin

if((char

return NUL L;

}else if(c har==p.Lch ar){

return p.Lch ild

}els e{

p=p.Lchild;

wh ile((pattern[i]>p.Rchar)&&(p!=NULL) )p=p.Rchild;

if(pattern[i]==p.Rchar)

r eturn p.Rchild;

els e

r eturn NULL;

}

End.

4.3 Marking the failure pointer

If the cur rent state node is p and goto(p,char)= N U L L,t he next state node is p.f ailstate.T he pr inciple o f failure point er is show n as follow s:

?T he failur e po inter of r oo t is ro ot.

?T he failur e point er of state node with stat e dept h1is ro ot too.

?F or all state node s who se stat e depth is gr eater than or equal to2:If the father stat e no de of s is r and g oto(r,a) =s,we can do follow pr og ram to mark the failure state node of s.

w hile(g oto((s.f ather state).f ailstate,a)==NU LL)s =s.f atherstate;

Finally,the failure point er o f s is s.f atherstate.

A s Figure4sho ws,t he failur e point ers are show n using do t lines.Ever y state no de has a failure po inter point ing to its failur e sta te node.Fo r ex ample,the failur e po inter o f state no de2points t o stat e no de0.T he algo r ithm3is used to mark the failur e po inter.

Algorithm3.Mark the failure pointer

Input:sequential binary tr ee who se ro ot node is s

Output:sequent ial bina ry tree w it h fa ilur e po inter

Build_F ail_Func(Str uctur e No de s)

Beg in

M ar k the failure point er o f st ate node s;

Build_F ail_Func(s.L child);

Build_F ail_Func(s.R child);

End

4.4 Adding and deleting node

In pr actice,the patter n set ma y be changed slig htly,fo r ex ample,adding o r deleting so me pat terns fro m t he set.I t is not w or thy of r ebuilding the w hole sequential binar y tr ee be-ca use o f t he slight change of pa tter n set,so the a dditions and deletions fro m sequentia l binar y tr ee are required.A fter ad-ditio ns and deletio ns,the failur e po inter must be changed ac-co rdingly.

If w e add o r delete a no de w ith state depth h,the failure po inter of ever y no de w ho se state depth is g reat er than h is pr obably to be cha ng ed.T hat is to sa y that part of failure po inter need cha ng ing.

5 Searching phase

5.1 Outputting the matching result

When a node s(s.outp ut==tr ue)is encounter ed in the sear ching pr ocess,w e visit the sequential binar y tr ee fr om ro ot t o s and output the content o f st ack a s t he matching r e-sult.L et no de f be the no de which is po inted by the failure po inter o f s.If f.outp ut==tr ue,sy nchr ono usly,we v isit the sequent ial binary tr ee fro m r oot to s and o utput the con-t ent of stack as the matching r esult.T here is a tr ace back in output pr ocess,so it affects the searching efficiency.

5.2 The description of searching algorithm

Aft er t he co nst ructio n of t he sequent ial binary tr ee,we can ex pediently f ind all patt erns fro m the tex t str ing by only scanning t he t ex t str ing once.T he sear ching pr ocess de-scr ibes as f ollo ws.Star ting fr om the ro ot of sequent ial binar y tree and select ing ever y char acter of t ext string o ne by one, we can det ermine the nex t state node acco rding t o g oto func-t ion and failure pointer.W e o utput the matching r esult w hen a node s(s.outp ut==tr ue)is enco unter ed in the sear ching pr ocess.T aking exam ple fo r t he sequential binar y t ree built in this paper,the pro cess o f sear ching"usher s"is descr ibed as fo llo ws:

Start ing fr om r o ot,go to(ro ot,u)=0.g oto(0,s)=13. go to(13,h)=14.go to(14,e)=15.No w,we o ut put the no de15,that is to output patter n"she".A t the same time, we o ut put t he no de2,that is to o ut put patter n"he".

We search the t ex t str ing fro m st ate no de2,because the failur e pointer of stat e no de15is sta te no de2.g oto(2,r)= 3.g ot o(3,s)=4.N ow,w e output t he no de4,that is to output pat tern"her s".T he searching pr ocess ends here.

T he fo llow ing algo rithm summarizes t he above behav-ior.

Algorithm4:Pattern matching algorithm

Input:tex t string"a1a2...a n"

T he sequential binary tr ee

Output:pat terns in tex t st ring and lo cat ions at which pat terns occur in t ex t str ing

p<--ro ot;

for i<--1unt il n{

w hile((p=goto(p,a i))==N U L L)do p<--p.f ailstate;

if(p.outp ut){

pr int i;pr int p;

1390 小 型 微 型 计 算 机 系 统 2004年

if(p.f ailstate.outp ut)

print p.f ailstate;

}

}

6 Analysis of algorithm

6.1 Analysis of space complexity

Compar ing to t raditional multiple patter n mat ching alg o-rithm,the SM A alg or ithm do esn?t need additio na l memor y space o f go to t able,fa ilur e table a nd output table because o f utilizing the sequential binar y tr ee.T he memor y space o f SM A algo rithm is only the to tal space o f all nodes of t he se-quential binar y tr ee.T her e are tw o facto rs t hat determine the number o f sequential binar y tree node:T he fir st one is the to tal leng th of all patt erns in pa tter n set.T he seco nd fac-tor is ho w many sharing pr efix of each patter n.So,the num-ber o f sequential binar y tr ee no des can?t be computed by fo r-mula analysis.

6.2 Analysis of time complexity

T he analysis o f time complexity is consisted o f the con-st ructio n phase and sear ching phase.In o r der t o descr ibe ex-pediently,let the number o f patt erns o f pat tern set be k,the number of nodes o f t he sequential binar y tr ee is m and the leng th of t ext str ing is n.

Construction phase

T he time complexity o f algo rithm1is deter mined pr i-marily by the o ut er loo p,so the time complex it y is O(k).

T he pr ocess o f mar king failure po inter o f ev ery node is show n in alg or ithm3.T he main pr ocess of alg or ithm3is to tr aver se the sequential binar y t ree accor ding t o N L R mo del, so it s t ime complexity is O(m).

In a w o rd,t he time co mplex ity of co nst ructio n phase is O(m+k).

Searching phase

T he sear ching phase o f SM A algo rithm is simila r to that of t raditional multiple patter n mat ching algo rithm.

T he o ut er loo p of algo rithm4is deter mined primarily by n(the leng th o f tex t st ring).T he time co nsuming o f ev er y loop is determined prim arily by the algo rit hm2.N o w,w e analy ze the time com plex ity of algo rithm2.

T he pro cess fr om father stat e no de t o o ne o f it s child state no de(s)is determined by t he num ber o f child state node (s).F or ex ample,the num ber of sear ching path is1,2and 3r espectively fr om st ate node0t o its child state no de1,10 and13.A ssuming that the aver age num ber o f child stat e node(s)o f ever y no de is h,the tim e co mplex ity o f alg or it hm 2is O(h/2)because of t he char acters o f searching path is sor ted in incr easing o rder[4].T he upper lim it of h is the size of languag e alphabet.F or ex ample,h is sm aller t han o r equal t o26in English lang uage igno ring of case.

In a w o rd,the time complexity of sear ching phase is O (hn/2).

7 Experimental result

T a ble1 Co ng tr uct ion o f time o f tw o algo rithm

algorith ms

diction aries NAM E NAM E

DNS

NAM E

DNS

ABBR Traditional

algorith m(T/m s)

270320440

S M A

algorith m(T/m s)

110130150

T he ex periment al sa mples include patter n set and tex t. T he patter n set includes N A M E dictio nary(8843names), DN S dict ionar y(1871Inter net address suffix es)and A BBR dictionar y(1470abbrev iations).T he text is do wnloaded fro m Eng lish news w ebsit e,which includes10k bytes,20k by tes,40k byt es and80k bytes tex t samples.T able1is the co nst ructio n time o f t wo a lg or ithms.T he constr uction time of SM A is half of that of t raditional multiple patter n match-ing algo rithm,w hich is fit for the conditio n of changing pat-t ern set dynamically.In this paper,w e sear ch fo ur t ext using three dictio nar ies respect ively and compute their av erag e time as sear ching time.A s t able2sho w s,the sear ching efficiency of tw o a lg or ithms is same and that o f t raditional alg or ithm is slow er slig htly than SM A algo rithm.It is o bv io us that the st or age st ructure o f SM A alg or ithm doesn?t affect its effi-ciency.

T able2 Cear ehing t ime of t wo algo rit hm

algorith ms

length10K20K40K80K Traditional

algorith m(T/m s)

143053115

S M A

algorith m(T/m s)

152050100

8 Conclusions

In o rder to meet the r equirement of co nstr uct ing au-t omata dy na mically,this paper or ig inally pr oposes the method to constr uct t he auto mata using sequential binar y tree.It is pr ov ed by ex per iment that the SM A algo rithm has a hig h constr uct ion rate and has a same sear ching efficiency with tr aditio nal alg or ithm.So t he SM A alg or it hm has a g oo d applicatio n pr ospect.

T he SM A algo rithm inspects ev ery char acter o f t ex t in sear ching pr https://www.360docs.net/doc/c518959638.html,bining Boyer-M oo re alg or ithm o r Quick Sear ch alg or ithm w ith SM A alg or ithm,we can imple-ment a skip-sear ching alg or it hm.A s for lar ge alphabet lan-

1391

7期 刘功申等:一种基于有序二叉树的多模式匹配算法

guag e,because the number o f child stat e no des of the ro ot node is ver y big,we can co nstr uct the fir st lev el st ate nodes using hash metho d,that is to say that we co nst ruct a for est w hich is co nsisted o f many sequential binar y tr ee.T he con-st ructio n method can sear ch t he t ext mor e quickly.

Ref erences:

1Aho A V,Corasick M J,Efficien t string matching:an aid to bib-liographic s earch[J].Com m.AC M,1975,18(6):333-340.

2L ew is H R,Pap adimitriou C H,Elemen ts of the theory of com-pu tation(S econd Edition)[M].Pr entice~Hall In ternation al, Inc.1998.3Fan J J,S u K Y,An efficien t algorithm for match multiple pat-terns[J].IEEE T rans.on Know ledge and Data En gineering, 1993,5(2):339-351.

4S haffer C A,A practice introduction to data structu res and algo-rithm analysis[M].New York Pren tice Hall,1997.

5Ch en Gui-lin.S ome technology research in autom atic abstract

[D].Sh ang hai Jiaotong University,Sh an ghai China,2000,4(In

Ch ines e).

6Boyer R S,M oore J S,A fast string searching algorithm[J].

Comm.ACM,1977,20(10):762-772.

7Su nday D M,A very fast su bstring search algorithm[J].Comm.

ACM,1990,33(8):132-142.

1392 小 型 微 型 计 算 机 系 统 2004年

模式匹配的KMP算法详解

模式匹配的KMP算法详解 模式匹配的KMP算法详解 这种由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现的改进的模式匹配算法简称为KMP算法。大概学过信息学的都知道,是个比较难理解的算法,今天特把它搞个彻彻底底明明白白。 注意到这是一个改进的算法,所以有必要把原来的模式匹配算法拿出来,其实理解的关键就在这里,一般的匹配算法: int Index(String S,String T,int pos)//参考《数据结构》中的程序 { i=pos;j=1;//这里的串的第1个元素下标是1 while(i<=S.Length && j<=T.Length) { if(S[i]==T[j]){++i;++j;} else{i=i-j+2;j=1;}//**************(1) } if(j>T.Length) return i-T.Length;//匹配成功 else return 0; } 匹配的过程非常清晰,关键是当‘失配’的时候程序是如何处理的?回溯,没错,注意到(1)句,为什么要回溯,看下面的例子: S:aaaaabababcaaa T:ababc aaaaabababcaaa ababc.(.表示前一个已经失配) 回溯的结果就是 aaaaabababcaaa a.(babc) 如果不回溯就是 aaaaabababcaaa aba.bc 这样就漏了一个可能匹配成功的情况 aaaaabababcaaa ababc 为什么会发生这样的情况?这是由T串本身的性质决定的,是因为T串本身有前后'部分匹配'的性质。如果T为abcdef这样的,大没有回溯的必要。

二叉树的各种算法

二叉树的各种算法.txt男人的承诺就像80岁老太太的牙齿,很少有真的。你嗜烟成性的时候,只有三种人会高兴,医生你的仇人和卖香烟的。 /*用函数实现如下二叉排序树算法: (1)插入新结点 (2)前序、中序、后序遍历二叉树 (3)中序遍历的非递归算法 (4)层次遍历二叉树 (5)在二叉树中查找给定关键字(函数返回值为成功1,失败0) (6)交换各结点的左右子树 (7)求二叉树的深度 (8)叶子结点数 Input 第一行:准备建树的结点个数n 第二行:输入n个整数,用空格分隔 第三行:输入待查找的关键字 第四行:输入待查找的关键字 第五行:输入待插入的关键字 Output 第一行:二叉树的先序遍历序列 第二行:二叉树的中序遍历序列 第三行:二叉树的后序遍历序列 第四行:查找结果 第五行:查找结果 第六行~第八行:插入新结点后的二叉树的先、中、序遍历序列 第九行:插入新结点后的二叉树的中序遍历序列(非递归算法) 第十行:插入新结点后的二叉树的层次遍历序列 第十一行~第十三行:第一次交换各结点的左右子树后的先、中、后序遍历序列 第十四行~第十六行:第二次交换各结点的左右子树后的先、中、后序遍历序列 第十七行:二叉树的深度 第十八行:叶子结点数 */ #include "stdio.h" #include "malloc.h" #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0

#define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int KeyType; #define STACK_INIT_SIZE 100 // 存储空间初始分配量 #define STACKINCREMENT 10 // 存储空间分配增量 #define MAXQSIZE 100 typedef int ElemType; typedef struct BiTNode{ ElemType data; struct BiTNode *lchild,*rchild;//左右孩子指针 } BiTNode,*BiTree; Status SearchBST(BiTree T,KeyType key,BiTree f,BiTree &p) { if(!T){p=f;return FALSE;} else if(key==T->data){p=T;return TRUE;} else if(keydata)return SearchBST(T->lchild,key,T,p); else return(SearchBST(T->rchild,key,T,p)); } Status InsertBST(BiTree &T,ElemType e) { BiTree s,p; if(!SearchBST(T,e,NULL,p)) { s=(BiTree)malloc(sizeof(BiTNode)); s->data=e;s->lchild=s->rchild=NULL; if(!p)T=s; else if(edata)p->lchild=s; else p->rchild=s; return TRUE; } else return FALSE; } Status PrintElement( ElemType e ) { // 输出元素e的值 printf("%d ", e ); return OK; }// PrintElement

实验三 二叉树的基本操作实现及其应用

二叉树的基本操作实现及其应用 一、实验目的 1.熟悉二叉树结点的结构和对二叉树的基本操作。 2.掌握对二叉树每一种操作的具体实现。 3.学会利用递归方法编写对二叉树这种递归数据结构进行处理的算法。 4.会用二叉树解决简单的实际问题。 二、实验内容 设计程序实现二叉树结点的类型定义和对二叉树的基本操作。该程序包括二叉树结构类型以及每一种操作的具体的函数定义和主函数。 1 按先序次序建立一个二叉树, 2按(A:先序 B:中序 C:后序)遍历输出二叉树的所有结点 以上比做,以下选做 3求二叉树中所有结点数 4求二叉树的深度 三、实验步骤 ㈠、数据结构与核心算法的设计描述 /* 定义DataType为char类型 */ typedef char DataType; /* 二叉树的结点类型 */ typedef struct BitNode { DataType data; struct BitNode *lchild,*rchild; }*BitTree; 相关函数声明: 1、/* 初始化二叉树,即把树根指针置空 */ void BinTreeInit(BitTree *BT) { BT=(BitTree)malloc(sizeof(BitNode)); BT->data=NULL; cout<<"二叉树初始化成功!"<>ch; if(ch=='#') BT=NULL; else { if(!(BT=(BitTree)malloc(sizeof(BitNode)))) exit(0);

字符串的模式匹配算法

在前面的图文中,我们讲了“串”这种数据结构,其中有求“子串在主串中的位置”(字符串的模式匹配)这样的算法。解决这类问题,通常我们的方法是枚举从A串(主串)的什么位置起开始与B串(子串)匹配,然后验证是否匹配。假设A串长度为n,B串长度为m,那么这种方法的复杂度是O(m*n)的。虽然很多时候复杂度达不到m*n(验证时只看头一两个字母就发现不匹配了),但是我们有许多“最坏情况”,比如: A=“aaaaaaaaaaaaaaaaaaaaaaaaab”,B=“aaaaaaaab”。 大家可以忍受朴素模式匹配算法(前缀暴力匹配算法)的低效吗?也许可以,也许无所谓。 有三位前辈D.E.Knuth、J.H.Morris、V.R.Pratt发表一个模式匹配算法,最坏情况下是O(m+n),可以大大避免重复遍历的情况,我们把它称之为克努特-莫里斯-普拉特算法,简称KMP算法。 假如,A=“abababaababacb”,B=“ababacb”,我们来看看KMP是怎样工作的。我们用两个指针i和j分别表示,。也就是说,i是不断增加的,随着i 的增加j相应地变化,且j满足以A[i]结尾的长度为j的字符串正好匹配B串的前j个字符(j当然越大越好),现在需要检验A[i+1]和B[j+1]的关系。 例子: S=“abcdefgab” T=“abcdex” 对于要匹配的子串T来说,“abcdex”首字符“a”与后面的串“bcdex”中任意一个字符都不相等。也就是说,既然“a”不与自己后面的子串中任何一字符相等,那么对于主串S来说,前5位字符分别相等,意味着子串T的首字符“a”不可能与S串的第2到第5位的字符相等。朴素算法步骤2,3,4,5的判断都是多余,下次的起始位置就是第6个字符。 例子: S=“abcabcabc” T=“abcabx”

模式匹配算法的设计与实现

五、详细设计 #include #include #include #include using namespace std; #define MAX 100000 #define M 69 class String { private: int n; char *str; int *count; //记录子串在主串中出现的位置 int Find(int i,String &P); // 简单匹配算法找到最近的匹配串后立即停止,而不向下继续且缺乏一个数组记录位置 int *f ; //记录失败函数 void Fail(); int KMPFind(int i,String &P); //改进的失败函数 void ImproveFail(); int KMPFindImprove(int i,String &P); public: String(); //建立一个空串 String(const char *p); String(const String &p); //拷贝函数 ~String(); int Length() {return n;}; //返回当前串对象长度 void Output() {cout<

int KMPFindImprove(String &P); //改进的KMP匹配算法 void Output2(); //输出子串在主串中出现的位置 }; int String::KMPFindImprove(String &P) { int sum=0; int j=KMPFindImprove(0,P); while(j!=-1) { count[sum++]=j; if(j<=n-P.n) j=KMPFindImprove(j+P.n,P); } return sum; } void String::Output2() //输出子串在主串中的位置 { int i=0; while(count[i]!=count[i+1] && i

二叉树的层次遍历算法

二叉树层次遍历算法实现 问题描述 对任意输入的表示某二叉树的字符序列,完成二叉树的层次遍历算法,并输出其遍历结果。 注:所需Queue ADT的实现见附录。 输入描述 从键盘上输入一串字符串,该字符串为二叉树的先序遍历结果,其中如果遍历到空树时用字符”#”代替。 输出描述 从显示器上输出二叉树的按层次遍历结果。 输入与输出示例 输入: +A##/*B##C##D## 输出: +A/*DBC 输入: ABD##GJ###CFH##I### 输出: ABCDGFJHI 附录(仅供参考): #include #include #define TRUE 1 #define FALSE 0 #define MAX_QUEUE_SIZE 100

//注:需要定义ElementType类型,如果是二叉树, // 则应定义为指向二叉树中结点的指针类型 //格式如: // typedef Tree ElementType; // 队列存储结构采用循环队列 struct QueueRecord; typedef struct QueueRecord *Queue; int IsEmpty(Queue Q); int IsFull(Queue Q); Queue CreateQueue(int MaxElements); void DisposeQueue(Queue Q); void MakeEmpty(Queue Q); int Enqueue(ElementType X, Queue Q); ElementType Front(Queue Q); int Dequeue(Queue Q, ElementType &X); #define MinQueueSize ( 5 ) struct QueueRecord { int Capacity; int Front; int Rear; ElementType *Array; }; int IsEmpty(Queue Q) { return ((Q->Rear + 1)% Q->Capacity == Q->Front); } int IsFull(Queue Q) { return ((Q->Rear + 2) % Q->Capacity == Q->Front); } Queue CreateQueue(int MaxElements) { Queue Q; if (MaxElements < MinQueueSize) return NULL; Q = (Queue)malloc(sizeof(struct QueueRecord));

实验三____串的模式匹配

实验三串的模式匹配 一、实验目的 1.利用顺序结构存储串,并实现串的匹配算法。 2.掌握简单模式匹配思想,熟悉KMP算法。 二、实验要求 1.认真理解简单模式匹配思想,高效实现简单模式匹配; 2.结合参考程序调试KMP算法,努力算法思想; 3.保存程序的运行结果,并结合程序进行分析。 三、实验内容 1、通过键盘初始化目标串和模式串,通过简单模式匹配算法实现串的模式匹配,匹配成功后要求输出模式串在目标串中的位置; 2、参考程序给出了两种不同形式的next数组的计算方法,请完善程序从键盘初始化一目标串并设计匹配算法完整调试KMP算法,并与简单模式匹配算法进行比较。 参考程序: #include "stdio.h" void GetNext1(char *t,int next[])/*求模式t的next值并寸入next数组中*/ { int i=1,j=0; next[1]=0; while(i<=9)//t[0] { if(j==0||t[i]==t[j]) {++i; ++j; next[i]=j; } else j=next[j]; } } void GetNext2(char *t , int next[])/* 求模式t 的next值并放入数组next中 */ { int i=1, j = 0; next[1]= 0; /* 初始化 */ while (i<=9) /* 计算next[i+1] t[0]*/ { while (j>=1 && t[i] != t[j] ) j = next[j]; i++; j++;

if(t[i]==t[j]) next[i] = next[j]; else next[i] = j; } } void main() { char *p="abcaababc"; int i,str[10]; GetNext1(p,str); printf("\n"); for(i=1;i<10;i++) printf("%d",str[i]); GetNext2(p,str); printf("\n"); for(i=1;i<10;i++) printf("%d",str[i]); printf("\n\n"); }

模式匹配KMP算法实验报告

实验四:KMP算法实验报告 一、问题描述 模式匹配两个串。 二、设计思想 这种由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现的改进的模式匹配算法简称为KM P算法。 注意到这是一个改进的算法,所以有必要把原来的模式匹配算法拿出来,其实理解的关键就在这里,一般的匹配算法: int Index(String S,String T,int pos)//参考《数据结构》中的程序 { i=pos;j=1;//这里的串的第1个元素下标是1 while(i<=S.Length && j<=T.Length) { if(S[i]==T[j]){++i;++j;} else{i=i-j+2;j=1;}//**************(1) } if(j>T.Length) return i-T.Length;//匹配成功 else return 0; } 匹配的过程非常清晰,关键是当‘失配’的时候程序是如何处理的?为什么要回溯,看下面的例子: S:aaaaabababcaaa T:ababc aaaaabababcaaa ababc.(.表示前一个已经失配) 回溯的结果就是 aaaaabababcaaa a.(babc) 如果不回溯就是 aaaaabababcaaa aba.bc 这样就漏了一个可能匹配成功的情况 aaaaabababcaaa ababc 这是由T串本身的性质决定的,是因为T串本身有前后'部分匹配'的性质。如果T为a bcdef这样的,大没有回溯的必要。 改进的地方也就是这里,我们从T串本身出发,事先就找准了T自身前后部分匹配的位置,那就可以改进算法。 如果不用回溯,那T串下一个位置从哪里开始呢? 还是上面那个例子,T为ababc,如果c失配,那就可以往前移到aba最后一个a的位置,像这样:

关于快速高效的模式匹配算法的剖析与改进

关于快速高效的模式匹配算法的剖析与改进 摘要:模式匹配算法是现代化网络入侵检测中的关键环节,本文主要介绍了几种常用的模式匹配算法,并在此基础上,提出一种更快捷、更高效的改进方法,以提高模式匹配的效率与质量,确保网络安全。 关键词:模式匹配入侵检测改进 随着我国计算机与网络技术的飞速发展,网络应用已涉及到人们生产、生活的各个领域,其重要性日益凸显。随之而来的网络攻击问题也备受关注,给网络安全性带来挑战。传统的网络防御模式,主要采取身份认证、防火墙、数据加密等技术,但是与当前网络发展不适应。在此背景下,入侵检测技术营运而生,并建立在模式匹配基础上,确保检测的快捷性、准确性,应用越来越广泛。 1、模式匹配原理概述 模式匹配是入侵检测领域的重要概念,源自入侵信号的层次性。结合网络入侵检测的底层审计事件,从中提取更高层次的内容。通过高层事件形成的入侵信号,遵循一定的结构关系,将入侵信号的抽象层次进行具体划分。入侵领域大师kumar将这种入侵信号划分为四大层次,并将每一个层次与匹配模式相对应。以下将分别对四大层次进行分析: (1)存在。只要存在审计事项,就可以证明入侵行为的发生,并深层次挖掘入侵企图。存在主要对应的匹配模式就是“存在模式”。可以说,存在模式就是在固定的时间内,检查系统中的特定状态,

同时判断系统状态。 (2)序列。一些入侵的发生,是遵循一定的顺序,而组成的各种行为。具体表现在一组事件的秩序上。序列对应的是“序列模式”,在应用序列模式检测入侵时,主要关注间隔的时间与持续的时间。 (3)规则。规则表示的是一种可以扩展的表达方式,主要通过and 逻辑表达来连接一系列的描述事件规则。一般适用于这种模式的攻击信号由相关活动组成,这些活动之间往往不存在事件的顺序关系。 (4)其他。其他模式是不包含前面几种方法的攻击,在具体应用过程中,难以与其他入侵信号进行模式匹配,大多为部分实现方式。 2、几种常用的模式匹配算法 2.1 ac算法 ac算法(aho-corasick)是一种可以同时搜索若干个模式的匹配算法,最早时期在图书馆书目查询系统中应用,效果良好。通过使用ac算法,实现了利用有限状态自动机结构对所有字符串的接收过程。自动机具有结构性特征,且每一个前缀都利用唯一状态显示,甚至可同时应用于多个模式的前缀中。如果文本中的某一个字符不属于模式中预期的下一个字符范围内,或者可能出现错误链接的指向状态等,那么最长模式的前缀同时也可作为当前状态相对应的后缀。ac算法的复杂性在于o(n),预处理阶段的复杂性则在于o(m)。在采取ac算法的有限状态自动机中,应该在每一个字符的模式串中分别建立节点,提高该算法的使用效率与质量。目前,应用有限

二叉树遍历算法的实现

二叉树遍历算法的实现 题目:编制二叉树遍历算法的实现的程序 一.需求分析 1.本演示程序中,二叉树的数据元素定义为非负的整型(unsigned int)数据,输 入-1表示该处没有节点 2.本演示程序输入二叉树数据均是按先序顺序依次输入 3.演示程序以用户和计算机对话方式执行,即在计算机终端上显示“提示信息” 之后,由用户在键盘上输入演示程序中规定的运算命令;相应的输入数据和运 算结果显示在其后 4.本实验一共包括三个主要程序,分别是:1)二叉树前序,中序,后序遍历递归 算法实现2)二叉树前序中序遍历非递归算法实现3)二叉树层次遍历算法实现 5.本程序执行命令包括:1)构建二叉树2)二叉树前序递归遍历3)二叉树中序 递归遍历4)二叉树后序递归遍历5)二叉树前序非递归遍历6)二叉树中序非 递归遍历7)二叉树层次遍历 6.测试数据 (1)7 8 -1 9 10 -1 -1 -1 6 11 -1 -1 12 13 -1 -1 14 -1 -1 (2)1 -1 -1 (3)7 8 -1 -1 9 -1 -1 二.概要设计 1.为实现二叉树的遍历算法,我们首先给出如下抽象数据类型 1)二叉树的抽象数据类型 ADT BiTree{ 数据对象D:D是具有相同特性的数据元素的集合 数据关系R: 若D=Φ,则R=Φ,称BiTree是空二叉树; 若D≠Φ,则R={H},H是如下二元关系: (1)在D中存在唯一的成为根的数据元素root,它在关系H下无前驱; (2)若D-{H}≠Φ,则存在D-{root}={D1,D r},且D1∩D r=Φ (3)若D1≠Φ,则D1中存在唯一的元素x1,∈H,且存在D1上的 关系H1?H;若Dτ≠Φ,则D r中存在唯一的元素x r,∈ H,且存在D r上的关系H r?H;H={,,H1,H r}; (4)(D1,{H1})是符合本定义的二叉树,成为根的左子树,(D r,{H r})是 一颗符合本定义的二叉树,成为根的右字树。 基本操作P: InitBiTree(&T); 操作结果:构造空二叉树 DestroyBiTree(&T) 初始条件;二叉树存在 操作结果:销毁二叉树 CreateBiTree(&T,definition);

串的模式匹配算法实验报告

竭诚为您提供优质文档/双击可除串的模式匹配算法实验报告 篇一:串的模式匹配算法 串的匹配算法——bruteForce(bF)算法 匹配模式的定义 设有主串s和子串T,子串T的定位就是要在主串s中找到一个与子串T相等的子串。通常把主串s称为目标串,把子串T称为模式串,因此定位也称作模式匹配。模式匹配成功是指在目标串s中找到一个模式串T;不成功则指目标串s中不存在模式串T。bF算法 brute-Force算法简称为bF算法,其基本思路是:从目标串s的第一个字符开始和模式串T中的第一个字符比较,若相等,则继续逐个比较后续的字符;否则从目标串s的第二个字符开始重新与模式串T的第一个字符进行比较。以此类推,若从模式串T的第i个字符开始,每个字符依次和目标串s中的对应字符相等,则匹配成功,该算法返回i;否则,匹配失败,算法返回0。 实现代码如下:

/*返回子串T在主串s中第pos个字符之后的位置。若不存在,则函数返回值为0./*T非空。 intindex(strings,stringT,intpos) { inti=pos;//用于主串s中当前位置下标,若pos不为1则从pos位置开始匹配intj=1;//j用于子串T中当前位置下标值while(i j=1; } if(j>T[0]) returni-T[0]; else return0; } } bF算法的时间复杂度 若n为主串长度,m为子串长度则 最好的情况是:一配就中,只比较了m次。 最坏的情况是:主串前面n-m个位置都部分匹配到子串的最后一位,即这n-m位比较了m次,最后m位也各比较了一次,还要加上m,所以总次数为:(n-m)*m+m=(n-m+1)*m从最好到最坏情况统计总的比较次数,然后取平均,得到一般情况是o(n+m).

设计一个完整的程序,实现二叉树的各种算法

实验6 实验目的: 1、掌握二叉树的所有算法 2、熟悉计算机英语和术语 实验步骤: 1、二叉树算法的模拟 2、完型填空 3、翻译 具体要求: 一、设计一个完整的程序,实现二叉树的各种算法 要求:/*用函数实现如下二叉排序树算法: (1)插入新结点 (2)前序、中序、后序遍历二叉树 (3)中序遍历的非递归算法 (4)层次遍历二叉树 (5)在二叉树中查找给定关键字(函数返回值为成功1,失败0) (6)交换各结点的左右子树 (7)求二叉树的深度 (8)叶子结点数 输入: 第一行:准备建树的结点个数n 第二行:输入n个整数,用空格分隔 第三行:输入待查找的关键字 第四行:输入待查找的关键字 第五行:输入待插入的关键字 输出: 第一行:二叉树的先序遍历序列 第二行:二叉树的中序遍历序列 第三行:二叉树的后序遍历序列 第四行:查找结果 第五行:查找结果 第六行~第八行:插入新结点后的二叉树的先、中、序遍历序列第九行:插入新结点后的二叉树的中序遍历序列(非递归算法) 代码: #include "stdio.h" #include "malloc.h" #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 typedef int Status; typedef int KeyType;

#define STACK_INIT_SIZE 100 // 存储空间初始分配量 #define STACKINCREMENT 10 // 存储空间分配增量 #define MAXQSIZE 100 typedef int ElemType; typedef struct BiTNode{ ElemType data; struct BiTNode *lchild,*rchild;//左右孩子指针 } BiTNode,*BiTree; Status SearchBST(BiTree T,KeyType key,BiTree f,BiTree &p) { if(!T){p=f;return FALSE;} else if(key==T->data){p=T;return TRUE;} else if(keydata)return SearchBST(T->lchild,key,T,p); else return(SearchBST(T->rchild,key,T,p)); } Status InsertBST(BiTree &T,ElemType e) { BiTree s,p; if(!SearchBST(T,e,NULL,p)) { s=(BiTree)malloc(sizeof(BiTNode)); s->data=e;s->lchild=s->rchild=NULL; if(!p)T=s; else if(edata)p->lchild=s; else p->rchild=s; return TRUE; } else return FALSE; } Status PrintElement( ElemType e ) { // 输出元素e的值 printf("%d ", e ); return OK; }// PrintElement Status PreOrderTraverse( BiTree T, Status(*Visit)(ElemType) ) { // 前序遍历二叉树T的递归算法,对每个数据元素调用函数Visit。 //补全代码,可用多个语句

串的朴素模式匹配算法(BF算法)

//算法功能:串的朴素模式匹配是最简单的一种模式匹配算法,又称为 Brute Force 算法,简称为BF算法 #include #include #define MAXL 255 #define FALSE 0 #define TRUE 1 typedef int Status; typedef unsigned char SString[MAXL+1]; //生成一个其值等于串常量strs的串T void StrAssign(SString &T, char *strs) { int i; T[0] = 0; //0号单元存储字串长度 for(i = 0; strs[i]; i++) //用数组strs给串T赋值 T[i+1] = strs[i]; T[0] = i; } //返回子串T在主串S中第pos个字符开始匹配的位置,若不存在,则返回0 int Index(SString S, SString T, int pos) { int i = pos, j = 1; while(i <= S[0] && j <= T[0]) { if(S[i] == T[j]) //继续比较后面的字符 { i++; j++; } else//指针回退,重新开始匹配 { i = i -j + 2; j = 1; } } if(j > T[0]) return i - T[0]; else return 0;

int main() { SString S, T; int m; char strs1[MAXL]; //建立主串S char strs2[MAXL]; //建立模式串T printf("请输入主串和子串:\n"); printf("主串S: "); scanf("%s", strs1); printf("子串T: "); scanf("%s", strs2); StrAssign(S, strs1); StrAssign(T, strs2); m = Index(S, T, 1); if(m) printf("主串 S = {%s}\n子串 T = {%s}\n在第 %d 个位置开始匹配!\n", strs1, strs2, m); else printf("主串 S = {%s}\n子串 T = {%s}\n匹配不成功!\n", strs1, strs2); return 0; }

二叉树的遍历算法实验报告

二叉树实验报告 09信管石旭琳 20091004418 一、实验目的: 1、理解二叉树的遍历算法及应用 2、理解哈夫曼树及其应用。 3、掌握哈夫曼编码思想。 二、实验内容: 1、建立二叉树二叉链表 2、实现二叉树递归遍历算法(中序、前序、后序) 3、求二叉树高度 4、求二叉树结点个数 5、求二叉树叶子个数 6、将序号为偶数的值赋给左子树 三、主要程序: #include #include typedef int ElemType; struct BiTNode { ElemType data; struct BiTNode *lch,*rch; }BiTNode,*BiTree; struct BiTNode *creat_bt1(); struct BiTNode *creat_bt2(); void preorder (struct BiTNode *t); void inorder (struct BiTNode *t); void postorder (struct BiTNode *t); void numbt (struct BiTNode *t); int n,n0,n1,n2; void main() { int k; printf("\n\n\n"); printf("\n\n 1.建立二叉树方法1(借助一维数组建立)"); printf("\n\n 2.建立二叉树方法2(先序递归遍历建立)"); printf("\n\n 3.先序递归遍历二叉树"); printf("\n\n 4.中序递归遍历二叉树"); printf("\n\n 5.后序递归遍历二叉树"); printf("\n\n 6.计算二叉树结点个数"); printf("\n\n 7.结束程序运行");

BM模式匹配算法图解

Boyer-Moore 经典单模式匹配算法 BM模式匹配算法-原理(图解) 由于毕业设计(入侵检测)的需要,这两天仔细研究了BM模式匹配算法,稍有心得,特此记下。 首先,先简单说明一下有关BM算法的一些基本概念。 BM算法是一种精确字符串匹配算法(区别于模糊匹配)。 BM算法采用从右向左比较的方法,同时应用到了两种启发式规则,即坏字符规则和好后缀规则,来决定向右跳跃的距离。 BM算法的基本流程: 设文本串T,模式串为P。首先将T与P进行左对齐,然后进行从右向左比较,如下图所示: 若是某趟比较不匹配时,BM算法就采用两条启发式规则,即坏字符规则和好后缀规则,来计算模式串向右移动的距离,直到整个匹配过程的结束。 下面,来详细介绍一下坏字符规则和好后缀规则。 首先,诠释一下坏字符和好后缀的概念。 请看下图:

图中,第一个不匹配的字符(红色部分)为坏字符,已匹配部分(绿色)为好后缀。 1)坏字符规则(Bad Character): 在BM算法从右向左扫描的过程中,若发现某个字符x不匹配,则按如下两种情况讨论: i. 如果字符x在模式P中没有出现,那么从字符x开始的m个文本显然不可能与P匹配成功,直接全部跳过该区域即可。 ii. 如果x在模式P中出现且出现次数>=1,则以该字符所在最右边位置进行对齐。 用数学公式表示,设Skip(x)为P右移的距离,m为模式串P的长度,max(x)为字符x在P中最右位置。 可以总结为字符x出现与否,将max(x)=0作为初值即可。

例1: 下图红色部分,发生了一次不匹配。 计算移动距离Skip(c) = m-max(c)=5 - 3 = 2,则P向右移动2位。 移动后如下图: 2)好后缀规则(Good Suffix): 若发现某个字符不匹配的同时,已有部分字符匹配成功,则按如下两种情况讨论: i. 如果在P中位置t处已匹配部分P'在P中的某位置t'也出现,且位置t'的前一个字符与位置t的前一个字符不相同,则将P右移使t'对应t方才的所在的位置。 ii. 如果在P中任何位置已匹配部分P'都没有再出现,则找到与P'的后缀P''相同的P的最长前缀x,向右移动P,使x对应方才P''后缀所在的位置。

数据结构课程设计--按层次遍历二叉树

数据结构课程设计--按层次遍历二叉树学号: 题目按层次遍历二叉树学院计算机科学与技术专业计算机科学与技术 班级 姓名 指导教师 2013年6月20日 1 1问题描述及要求 (4) 1.1问题描述 (4) 1.2任务要求.................................. 4 2 开发平台及所使用软件.............................. 4 3 程序设计思路.. (5) 3.1二叉树存储结构设计 (5) 3.2题目算法设

计 (5) 3.2.1 建立二叉树 (5) 3.2.2 遍历二叉树 (5) 3.3.3 按要求格式输出已建立的二叉 树 (6) 3.3 测试程序................................ 6 4 调试 报告.................................... 6 5 经验和体会.................................. 6 6 源程序清单及运行结果 (7) 6.1 源程序清单 (7) 6.2 运行结果................................ 9 7 参考文献................................... 10 本科生课程设计成绩评定表 (11) 2 课程设计任务书 学生姓名:专业班级:计科ZY1102班指导教师:工作单位:计算机科学系题目: 按层次遍历二叉树 初始条件:

编写按层次顺序(同一层自左至右)遍历二叉树的算法。 (1)二叉树采用二叉链表作为存储结构。 ⑵按严蔚敏《数据结构习题集(C语言版)》p44面题6.69所指定的格式输出建立的二叉树。 (3)输出层次遍历结果。 (4)自行设计测试用例。 要求完成的主要任务: (包括课程设计工作量及其技术要求,以及说明书撰写等具体要求) 课程设计报告按学校规定格式用A4纸打印(书写),并应包含如下内容:1.问题描述 简述题目要解决的问题是什么。 2. 设计 存储结构设计、主要算法设计(用类C/C++语言或用框图描述)、测试用例设计; 3. 调试报告 调试过程中遇到的问题是如何解决的; 对设计和编码的讨论和分析。 4. 经验和体会(包括对算法改进的设想) 5. 附源程序清单和运行结果。源程序要加注释。如果题目规定了测试数据,则运行结 果要包含这些测试数据和运行输出。 说明: 1. 设计报告、程序不得相互抄袭和拷贝; 若有雷同,则所有雷同者成绩均为0 分。 2. 凡拷贝往年任务书或课程设计充数者,成绩一律无效,以0 分记。时间安排: 1(第17周完成,验收时间由指导教师指定

KMP字符串模式匹配算法解释

个人觉得这篇文章是网上的介绍有关KMP算法更让人容易理解的文章了,确实说得很“详细”,耐心地把它看完肯定会有所收获的~~,另外有关模式函数值next[i]确实有很多版本啊,在另外一些面向对象的算法描述书中也有失效函数f(j)的说法,其实是一个意思,即next[j]=f(j-1)+1,不过还是next[j]这种表示法好理解啊: KMP字符串模式匹配详解 KMP字符串模式匹配通俗点说就是一种在一个字符串中定位另一个串的高效算法。简单匹配算法的时间复杂度为O(m*n);KMP匹配算法。可以证明它的时间复杂度为O(m+n).。 一.简单匹配算法 先来看一个简单匹配算法的函数: int Index_BF ( char S [ ], char T [ ], int pos ) { /* 若串S 中从第pos(S 的下标0≤pos

JAVA实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法

本文由我司收集整编,推荐下载,如有疑问,请与我司联系JAVA 实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法 JAVA 实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法如图所 示一颗二叉树,用JAVA 实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历 算法 定义树节点 public class TreeNode { int data; TreeNode leftChild; TreeNode rightChild; TreeNode(){ this.leftChild=null; this.rightChild=null; this.data=-1; TreeNode(int data){ this.leftChild=null; this.rightChild=null; this.data=data; public TreeNode(int data, TreeNode leftChild, TreeNode rightChild) { this.data = data; this.leftChild = leftChild; this.rightChild = rightChild; //其它代码省略……二叉树的前序遍历、中序遍历、后 序遍历和层次遍历算法设计 package com.bean.binarytreedemo;import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.Stack; //给定一个一维数组,表示二叉树节点的值private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; private static List TreeNode nodeList = null; public void createBinTree() { nodeList = new LinkedList TreeNode // 将一个数组的值依次转换为Node 节点for (int nodeIndex = 0; nodeIndex array.length; nodeIndex++) { nodeList.add(new TreeNode(array[nodeIndex])); // 对前lastParentIndex-1 个父节点按照父节点与孩子节点的数字关系建立二叉树for (int parentIndex = 0; parentIndex array.length / 2 - 1; parentIndex++) { // 左孩子nodeList.get(parentIndex).leftChild = nodeList .get(parentIndex * 2 + 1); // 右孩子nodeList.get(parentIndex).rightChild = nodeList .get(parentIndex * 2 + 2); // 最后一个父节点:因为最后一个父节点可能没 有右孩子,因此单独拿出来处理int lastParentIndex = array.length / 2 - 1; // 左孩子nodeList.get(lastParentIndex).leftChild = nodeList .get(lastParentIndex * 2 + 1); // 右孩子,如果数组的长度为奇数才建立右孩子if (array.length % 2 == 1) {

相关文档
最新文档