Leetcode 1967. Number of Strings That Appear as Substrings in Word
Given an array of strings patterns
and a string word
, return the number of strings in patterns
that appear as substrings in word
.
word
and for each string in patterns
?
word
can be up to (10^3) and the length of each pattern can be up to (100).patterns
be empty?
patterns
will be non-empty.patterns
contain duplicate strings?
patterns
.word
.word
.#include <iostream>
#include <vector>
#include <string>
class Solution {
public:
int numOfStrings(std::vector<std::string>& patterns, std::string word) {
int count = 0;
for (const std::string& pattern : patterns) {
if (word.find(pattern) != std::string::npos) {
count++;
}
}
return count;
}
};
int main() {
Solution sol;
std::vector<std::string> patterns = {"a", "abc", "bc", "d"};
std::string word = "abc";
std::cout << sol.numOfStrings(patterns, word) << std::endl; // Output: 3
return 0;
}
n
is the length of word
and m
is the length of pattern) using the find
method in C++ STL.k
is the number of patterns, n
is the length of word
, and m
is the maximum length of any pattern.This solution iterates through each pattern and checks if it exists in the word
by leveraging the find
method from the C++ STL, making it straightforward and easily understandable.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?