KMP Algorithm 1
KMP Algorithm 1
TECH
Computer Science
Straightforward solution
Algorithm: Simple string matching Input: P and T, the pattern and text strings; m, the length of P. The pattern is assumed to be nonempty. Output: The return value is the index in T where a copy of P begins, or -1 if no match for P is found.
int match //value to return. int i,j,k; match = -1; j=1;k=1; i=j; while(endText(T,j)==false) if( k>m ) match = i; //match found. break; if(tj == pk) j++; k++; else //Back up over matched characters. int backup=k-1; j = j-backup; k = k-backup; //Slide pattern forward,start over. j++; i=j; return match;
Analysis
Worst-case complexity is in (mn) Need to back up. Works quite well on average for natural language.
Finite Automata
Terminologies
: the alphabet *: the set of all finite-length strings formed using characters from . xy: concatenation of two strings x and y. Prefix: a string w is a prefix of a string x if x=wy for some string y *. Suffix: a string w is a suffix of a string x if x= yw for some string y *.
Algorithm
Strategy
In general, if there is a partial match of j chars starting at i, then we know what is in position T[i]T[i+j-1]. So we can save by
Skip outer iterations (for which no match possible) Skip inner iterations (when no need to test know matches).
1. 2.
When a mismatch occurs, we want to slide P forward, but maintain the longest overlap of a prefix of P with a suffix of the part of the text that has matched the pattern so far. KMP algorithm achieves linear time performance by capitalizing on the observation above, via building a simplified finite automaton: each node has only two links, success and fail.
Analysis
KMP Flowchart Construction require 2m 3 character comparisons in the worst case The scan algorithm requires 2n character comparisons in the worst case Overall: Worst case complexity is (n+m)
Algorithm:Computing Jumps for the Boyer-Morre Algorithm Input:Pattern string P:m the length of P;alphabet size alpha=|| Output:Array charJump,defined on indexes 0,....,alpha-1.The array is passed in and the algorithm fills it. void computeJumps(char[] P,int m,int alpha,int[] charJump) char ch; int k; for (ch=0;ch<alpha;ch++) charJump[ch]=m; for (k=1;k<=m;k++) charJump[pk]=m-k;
Computing matchJump
BoyerMooreScan Algorithm
Summary
Straightforward algorithm: O(nm) Finite-automata algorithm: O(n) KMP algorithm: O(n+m)
Relatively easier to implement Do not require random access to the text