2185. 统计包含给定前缀的字符串
2185. 统计包含给定前缀的字符串
🟢 🔖 数组 字符串 字符串匹配 🔗 力扣 LeetCode
题目
You are given an array of strings words and a string pref.
Return the number of strings inwords that containpref as aprefix.
A prefix of a string s is any leading contiguous substring of s.
Example 1:
Input: words = ["pay","at tention","practice","at tend"], pref = "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "at tention" and "at tend".
Example 2:
Input: words = ["leetcode","win","loops","success"], pref = "code"
Output: 0
Explanation: There are no strings that contain "code" as a prefix.
Constraints:
1 <= words.length <= 1001 <= words[i].length, pref.length <= 100words[i]andprefconsist of lowercase English letters.
题目大意
给你一个字符串数组 words 和一个字符串 pref 。
返回 words 中以 pref 作为 前缀 的字符串的数目。
字符串 s 的 前缀 就是 s 的任一前导连续字符串。
示例 1:
输入: words = ["pay","at tention","practice","at tend"], pref = "at"
输出: 2
解释: 以 "at" 作为前缀的字符串有两个,分别是:"at tention" 和 "at tend" 。
示例 2:
输入: words = ["leetcode","win","loops","success"], pref = "code"
输出: 0
解释: 不存在以 "code" 作为前缀的字符串。
提示:
1 <= words.length <= 1001 <= words[i].length, pref.length <= 100words[i]和pref由小写英文字母组成
解题思路
- 初始化计数器:
count用于统计满足条件的单词数量。 - 遍历单词:使用
for...of遍历words中的每个单词。 - 检查前缀:使用
startsWith方法判断单词是否以pref开头。 - 更新计数器:如果满足条件,计数器
count增加。 - 返回结果:最后返回满足条件的单词数量。
复杂度分析
- 时间复杂度:
O(m * n),其中m是words的长度,n是pref的长度,对于每个单词,startsWith方法最多需要检查前缀的长度n。 - 空间复杂度:
O(1),只使用了一个计数器变量,没有额外的存储需求。
代码
/**
* @param {string[]} words
* @param {string} pref
* @return {number}
*/
var prefixCount = function (words, pref) {
let count = 0; // 初始化计数器
for (let word of words) {
// 遍历每个单词
if (word.startsWith(pref)) {
// 检查是否以 pref 为前缀
count++; // 如果满足条件,计数器 +1
}
}
return count; // 返回最终计数结果
};
相关题目
| 题号 | 标题 | 题解 | 标签 | 难度 | 力扣 |
|---|---|---|---|---|---|
| 1455 | 检查单词是否为句中其他单词的前缀 | [✓] | 双指针 字符串 字符串匹配 | 🟢 | 🀄️ 🔗 |
| 2255 | 统计是给定字符串前缀的字符串数目 | [✓] | 数组 字符串 | 🟢 | 🀄️ 🔗 |
