If you were doing this by hand, how would you answer your question? Keep in mind you'd have to remember the previous line you'd read, and you'd also have to remember if the previous line had matched the specified input.
If you can write out the steps, you can write the code.