I will guide you to solve your requirements, this is just a logic you have to create your own code...
1) Create a loop for all the pages in your document //for loop
2) Create a loop for all the textframes in each page //for loop
3) Then create a loop for all the lines in each textframes //for loop
4) Then store the last word of first line in a variable //var declaration
5)Store the last word of second line a variable //var declaration
6) Check the two words are equal //if condition
7) if the words are equal -> store the last word of third line in a variable //var declaration
8) Then check the third line last versus second line last word... //if condition
9) If true, you got the result, words are stacked for three lines //if condition
Vandy