跳至主要內容

1967. 作为子字符串出现在单词中的字符串数目


1967. 作为子字符串出现在单词中的字符串数目

🟢   🔖  数组 字符串  🔗 力扣open in new window LeetCodeopen in new window

题目

Given an array of strings patterns and a string word, return _thenumber of strings in _patterns _that exist as asubstring in _word.

A substring is a contiguous sequence of characters within a string.

Example 1:

Input: patterns = ["a","abc","bc","d"], word = "abc"

Output: 3

Explanation:

  • "a" appears as a substring in "a bc".
  • "abc" appears as a substring in "abc ".
  • "bc" appears as a substring in "a bc ".
  • "d" does not appear as a substring in "abc".

3 of the strings in patterns appear as a substring in word.

Example 2:

Input: patterns = ["a","b","c"], word = "aaaaabbbbb"

Output: 2

Explanation:

  • "a" appears as a substring in "a a aaabbbbb".
  • "b" appears as a substring in "aaaaabbbb b ".
  • "c" does not appear as a substring in "aaaaabbbbb".

2 of the strings in patterns appear as a substring in word.

Example 3:

Input: patterns = ["a","a","a"], word = "ab"

Output: 3

Explanation: Each of the patterns appears as a substring in word "a b".

Constraints:

  • 1 <= patterns.length <= 100
  • 1 <= patterns[i].length <= 100
  • 1 <= word.length <= 100
  • patterns[i] and word consist of lowercase English letters.

题目大意

给你一个字符串数组 patterns 和一个字符串 word ,统计 patterns 中有多少个字符串是 word 的子字符串。返回字符串数目。

子字符串 是字符串中的一个连续字符序列。

示例 1:

输入: patterns = ["a","abc","bc","d"], word = "abc"

输出: 3

解释:

  • "a" 是 "a bc" 的子字符串。
  • "abc" 是 "abc " 的子字符串。
  • "bc" 是 "a bc " 的子字符串。
  • "d" 不是 "abc" 的子字符串。

patterns 中有 3 个字符串作为子字符串出现在 word 中。

示例 2:

输入: patterns = ["a","b","c"], word = "aaaaabbbbb"

输出: 2

解释:

  • "a" 是 "a a aaabbbbb" 的子字符串。
  • "b" 是 "aaaaabbbb b " 的子字符串。
  • "c" 不是 "aaaaabbbbb" 的字符串。

patterns 中有 2 个字符串作为子字符串出现在 word 中。

示例 3:

输入: patterns = ["a","a","a"], word = "ab"

输出: 3

解释: patterns 中的每个字符串都作为子字符串出现在 word "a b" 中。

提示:

  • 1 <= patterns.length <= 100
  • 1 <= patterns[i].length <= 100
  • 1 <= word.length <= 100
  • patterns[i]word 由小写英文字母组成

解题思路

  1. 初始化计数器 count 为 0,用于记录符合条件的子串数量。
  2. 遍历 patterns 数组中的每个模式 pattern
    • 如果 word 包含 pattern,将 count 加 1。
  3. 遍历结束后,返回 count

复杂度分析

  • 时间复杂度O(m * n)

    • 遍历 patterns 的时间复杂度是 O(m),其中 mpatterns 的长度。
    • 对每个 pattern 调用 .includes() 方法的时间复杂度为 O(n),其中 nword 的长度。
    • 总体时间复杂度为 O(m * n)
  • 空间复杂度O(1),使用了常量空间。

代码

/**
 * @param {string[]} patterns
 * @param {string} word
 * @return {number}
 */
var numOfStrings = function (patterns, word) {
	let count = 0;
	for (let pattern of patterns) {
		if (word.includes(pattern)) {
			count++;
		}
	}
	return count;
};