classSolution { public: intnumOfStrings(vector<string>& patterns, string word){ auto check = [](const string& pattern, const string& word) -> bool{ int m = pattern.size(); int n = word.size(); for (int i = 0; i + m <= n; ++i){ bool flag = true; for (int j = 0; j < m; ++j){ if (word[i + j] != pattern[j]){ flag = false; break; } } if (flag){ returntrue; } } returnfalse; };
int res = 0; for (const string& pattern : patterns){ res += check(pattern, word); } return res; } };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defnumOfStrings(self, patterns: List[str], word: str) -> int: defcheck(pattern: str, word: str) -> bool: m = len(pattern) n = len(word) for i inrange(n - m + 1): flag = True for j inrange(m): if word[i + j] != pattern[j]: flag = False break if flag: returnTrue returnFalse res = 0 for pattern in patterns: res += check(pattern, word) return res
复杂度分析
时间复杂度:O(n \times \sum_i m_i),其中 n 为字符串 word 的长度,m_i 为字符串 patterns}[i] 的长度。
对于 patterns 中的每个字符串 patterns}[i],暴力匹配判断是否为 word 子串的时间复杂度为 O(n \times m_i)。
空间复杂度:O(1)。
方法二:KMP 算法
思路与算法
在方法一中,每一次调用函数 check}(\textit{pattern}, \textit{word}) 进行判断都需要暴力比较 pattern 与 word 中所有长度为 m 的子串,假设 word 的长度为 n,则匹配的时间复杂度为 O(nm)。