It's actually a little bit tricky to do this correctly and efficiently, because you can have the within k words matching on either side of the word, and you have have to keep track of things for the right number of words on each side. 