More Related Content Similar to 06. string matching Similar to 06. string matching (20) More from Onkar Nath Sharma More from Onkar Nath Sharma (9) 06. string matching2. String Matching Algorithms & Complexity
Weformalizethestring-matchingproblemasfollows.WeassumethatthetextisanarrayT[1..n]oflengthnandthatthepatternisanarrayP[1..m]oflengthm≤n.WefurtherassumethattheelementsofPandTarecharactersdrawnfromafinitealphabetΣ. Forexample,wemayhaveΣ={0,1}orΣ={a,b,...,z}.ThecharacterarraysPandTareoftencalledstringsofcharacters. 3. String Matching Algorithms
WesaythatpatternPoccurswithshiftsintextT(or,equivalently,thatpatternPoccursbeginningatpositions+1intextT)if0≤s≤n−mandT[s+1..s+m]=P[1..m](thatis,ifT[s+j]=P[j],for1≤j≤m).
IfPoccurswithshiftsinT,thenwecallsavalidshift;otherwise,wecallsaninvalidshift.Thestring-matchingproblemistheproblemoffindingallvalidshiftswithwhichagivenpatternPoccursinagiventextT.Figure32.1illustratesthesedefinitions. 5. The Naive string-matching algorithm
ThenaivealgorithmfindsallvalidshiftsusingaloopthatcheckstheconditionP[1..m]=T[s+1..s+m]foreachofthen−m+1possiblevaluesofs.
Procedure NAIVE-STRING-MATCHER takes time O((n −m + 1)m), and this bound is tight in the worst case.