1967.作为子字符串出现在单词中的字符串数目:遍历枚举

【LetMeFly】1967.作为子字符串出现在单词中的字符串数目:遍历枚举

力扣题目链接:https://leetcode.cn/problems/number-of-strings-that-appear-as-substrings-in-word/

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

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

 

示例 1:

输入:patterns = ["a","abc","bc","d"], word = "abc"
输出:3
解释:
- "a" 是 "abc" 的子字符串。
- "abc" 是 "abc" 的子字符串。
- "bc" 是 "abc" 的子字符串。
- "d" 不是 "abc" 的子字符串。
patterns 中有 3 个字符串作为子字符串出现在 word 中。

示例 2:

输入:patterns = ["a","b","c"], word = "aaaaabbbbb"
输出:2
解释:
- "a" 是 "aaaaabbbbb" 的子字符串。
- "b" 是 "aaaaabbbbb" 的子字符串。
- "c" 不是 "aaaaabbbbb" 的字符串。
patterns 中有 2 个字符串作为子字符串出现在 word 中。

示例 3:

输入:patterns = ["a","a","a"], word = "ab"
输出:3
解释:patterns 中的每个字符串都作为子字符串出现在 word "ab" 中。

 

提示:

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

解题方法:遍历枚举

遍历一遍parttens字符串,看看哪个pattern被包含在word中。

语言 库函数
C++23 word.contains(p)
java word.contains(p)
rust word.contains(p)
python p in word
go strings.Contains(word, p)
  • 时间复杂度$O(nL)$,其中$n=len(word)$,$L=\sum len(patterns_i)$
  • 空间复杂度$O(1)$

AC代码

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
/*
* @LastEditTime: 2026-06-29 15:07:50
*/
class Solution {
public:
int numOfStrings(vector<string>& patterns, string& word) {
int ans = 0;
for (string& p : patterns) {
ans += word.contains(p);
}
return ans;
}
};

Python

1
2
3
4
5
6
7
8
'''
LastEditTime: 2026-06-29 15:19:06
'''
from typing import List

class Solution:
def numOfStrings(self, patterns: List[str], word: str) -> int:
return sum(p in word for p in patterns)

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
* @LastEditTime: 2026-06-29 15:23:03
*/
class Solution {
public int numOfStrings(String[] patterns, String word) {
int ans = 0;
for (String p : patterns) {
if (word.contains(p)) {
ans++;
}
}
return ans;
}
}

Go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/*
* @LastEditTime: 2026-06-29 15:20:20
*/
package main

import "strings"

func numOfStrings(patterns []string, word string) (ans int) {
for _, p := range patterns {
if strings.Contains(word, p) {
ans++
}
}
return
}

Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*
* @LastEditTime: 2026-06-29 15:22:08
*/
impl Solution {
pub fn num_of_strings(patterns: Vec<String>, word: String) -> i32 {
let mut ans = 0;
for p in patterns.iter() {
if word.contains(p) {
ans += 1;
}
}
ans
}
}

同步发文于CSDN和我的个人博客,原创不易,转载经作者同意后请附上原文链接哦~

千篇源码题解已开源


1967.作为子字符串出现在单词中的字符串数目:遍历枚举
https://blog.letmefly.xyz/2026/06/29/LeetCode 1967.作为子字符串出现在单词中的字符串数目/
作者
发布于
2026年6月29日
许可协议