Algorithm: Boyer/Moore with Occurrence Check

/* Computation of the Shift-Table (phase 1) */
rborder[m] := 0
D[m] := 0
FOR j := m-1 DOWNTO 0 DO
  rborder[j] := 1
  D[j] := m
END
j = 1
i = m-1
WHILE i >= j DO
  WHILE i >= j AND pat[m-j+1] = pat[i-j+1] DO
    j := j+1
    rborder[i-j+1] := j
  END
  IF j > 1 THEN
    D[m-j+1] = MIN(m-i, D[m-j+1])
  ENDIF
  i := i-j+rborder[m-j+1]
  j := MAX(rborder[m-j+1], 1)
END

/* Computation of the Shift-Table (phase 2) */
t := rborder[0]
L := 1
WHILE t > 0 DO
  s = m-t+1
  FOR j := L TO s DO
    D[j] := MIN(D[j], s
  END
  t := rborder[s]
  L := s+1
END

/* Computation of the last table */
FOR c := 'a' TO 'Z' DO
  last[c] := 0;
END
i := 1
WHILE i <= m DO
  last[pat[i]] = i
  i := i+1
END

/* Algorithm: Boyer/Moore with Occurrence Check*/
i := 1
WHILE i <= n-m+1 DO
  j := m
  WHILE j >= 1 AND pat[j] = text[i+j-1] DO
    j := j-1
  END
  IF j = 0 THEN RETURN TRUE
  i := i+MAX(D[j], j-last[text[i+j-1]])
END
RETURN FALSE

Time complexity: O (n+m)
Space complexity: O (m)


Back to the Applet