String Algorithms
Print this page

Algorithm For Brute-Force String matching

Let P[0..m] is the given pattern and T[0..n] is the text.
 
  1. i = 1; [ substring 1]
  2. Repeat steps 3 to 5 while i <=n-m+1 do
  3. for j= 1 to m [For each character of P]

    If P[j] != T[i+j-1] then
    goto step 5

  4. Print "Pattern found at shift i "
  5. i= i + 1
  6. exit
     
         
  • The complexity of the brute force string matching algorithm is O(nm)
  • On average the inner loop runs fewer than m times to know that there is a mismatch.
  • The worst case situation arises when first m character are matched for all substrings Si. If pattern is of the am-1b and text is of the form an-1b, where an-1 denotes a repeated n -1 times. In this case the inner loop runs exactly for m times before knowing that there is a mismatch. In this situation there will be exactly m*(n-m+1) number of comparisons.
Prev