Can the previous algorithm be used for any other string instead of abcd?
A problem arises when the pattern contains repetitions. For example, suppose we are looking for substring ababc. Assume that a appears, then b, a, and b again. At this point, we are eagerly waiting for e. If the letter d appears instead, we should start from scratch. However, if the letter a appears, we still have a chance that b and c follow and the pattern is found.
Here is an illustration:
x y z a b a b a b c … ← input string
a b a b c ← pattern was expected here
a b a b c ← but it is here
In other words, at the point
there are two possible pattern positions to be tested.