I used state machine concept. Identified 5 different states using two character combination.
See this in my solution
Explaination:
State is represented by two state variables a and b.
if the string is ending at b then a is zero (to indicate
the end state). If a is not zero then a and b represent
the last two point (character) states when b is
not the end point, but a is the end point.
So (0, 1) and (0, 2) means the good string is ending at character 1
and 2 respectively.
The valid states can be
(2, 1) when it is like (***21) and from b(1) the dog can jumps to
a(2) and so a(2) is the end point, not the last character b(1).
(2, 2) when it is like (**22) and dog is at the a(2) and b(2) is
unvisited character.
So moving to next character is like state transition, this will be
clear by following example:

String is in state (0, 1) and the next character is ‘2’, then the new
state would be (0, 2). 
Current state is (2, 1) and the next character is ‘2’, the new state
would be (0, 2). 
Current state is (2, 1) the the next character is ‘1’ then the new
state would be (0, 1). 
Current state is (2, 2) and the next character is ‘1’ then the new state
would be (2, 1).
This is explained in the code.