- For each index
offsetstart
in the input string from 0 tosword.size() - pattern.size() + 1
. The idea here is that near the end of the word when there are not enough characters to match the pattern, stop the loop.- For each
index
in the pattern- If
s[offsetword[start + index] != pattern[index]
then break out of this inner loop, and continue from the nextoffset
in the outer loop atstart + 1
- If
- If the end of the inner loop is reached without ever braking out, then a match was found, return true immediately
- For each
- If the end of the outer loop is reached, then there was no match, return false
Putting that into code:
bool isSubstr(const std::string & word, const std::string & pattern)
{
for (auto start = 0; start < word.size() - pattern.size() + 1; start++)
{
bool found = true;
for (auto i = 0; i < pattern.size(); i++)
{
if (word[start + i] != pattern[i])
{
found = false;
break;
}
}
if (found)
{
return true;
}
}
return false;
}
To avoid using the flag variable found
, we can move the inner loop into a separate function,
which instead of setting a flag variable + break,
returns false immediately: