Hello @Jennifer_Herrarte
Let’s understand the logic with the help of an example. Let’s suppose str
is catfoxcat
and words to look for are ["cat", "fox"]
. str.length
would be 9
and wordsCount
will be 2
and wordLength
will be 3
. Hence, the total length for words to look for becomes 3*2 = 6.
So essentially, at every index we will be checking if the next 6 characters (including the current one) match the words. But we also have to take care of index out of bounds error. For instance, if we are at the last index we cannot check for next 6 indices.
So this condition just specifies how many iterations we can make on str
and match the total length of words in the list. In this case, we can move 4 times as follows:
- catfox
- atfoxc
- tfoxca
- foxcat
So loop will run from index 0 to index 3 only.
Hope this helps!