So we'd write a for-loop and check that each index is equal until the shorter word is completed.
What if we wanted to know if graph
was in geography
? We would still write a for-loop that compares the characters at each index, but we need to account for if there is a match later on.
Here, we can use the two-pointer technique
we learned about prior! Why don't we use another pointer for the purpose of seeing how far we can "extend our match" when we find an initial one?
xxxxxxxxxx
13
let j = 0;
let str = 'digginn';
let subStr = 'inn';
​
for (i = 0; i < str.length; i++) {
// if match, compare next character of subStr with next of string
if (str[i] == subStr[j]) {
j++;
// else no need to see how far to extend
} else {
j = 0;
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment