I am solving this problem where the function returns the number of times a pattern is found in a said string word
. It could be easily solved via std::find
but I wanted to implement the logic myself and see if I bring in some improvements but turns out my solution fares worst than with std::find
.
The solution works but I am wondering if it could be improved upon. The current time complexity I reckon is O(N*M) where N
= elems of pattern, M
= elems of word.
// Sample input
pattern: ["a","abc","bc","d"]
word: "abc"
// Sample output
3
bool isSubstr(string word, string pattern)
{
int wordIdx = 0;
int pattIdx = 0;
size_t pattSz = pattern.size();
for (int i=0; i<word.size(); i++)
{
int curI = i;
// iterate over word as long as each letter matches with pattern's
while (i < word.size() && pattern[pattIdx] == word[i])
{
pattIdx++;
i++;
}
// ... we have found a pattern
if (pattIdx == pattSz)
{
return true;
}
// a full pattern wasn't found but a part of it was. Reset the i
if (i != curI)
{
pattIdx = 0;
i = curI;
}
}
return false;
}
int containsSubStr(vector<string>& patterns, string word)
{
int count = 0;
for (auto& pattern : patterns)
{
if (isSubstr(word, pattern))
{
count++;
}
}
return count;
}
p.s: I understand the importance of prefixing the containers with std::
but this is not a production code and rather merely an interview question