LC 2185.Counting Words With a Given Prefix

题目描述

这是 LeetCode 上的 2185. 统计包含给定前缀的字符串 ,难度为简单

给你一个字符串数组 words 和一个字符串 pref

返回 words 中以 pref 作为 前缀 的字符串的数目。

字符串 s前缀 就是 s 的任一前导连续字符串。

示例 1:

1
2
3
输入:words = ["pay","attention","practice","attend"], pref = "at"
输出:2
解释:以 "at" 作为前缀的字符串有两个,分别是:"attention" 和 "attend" 。

示例 2:

1
2
3
输入:words = ["leetcode","win","loops","success"], pref = "code"
输出:0
解释:不存在以 "code" 作为前缀的字符串。

提示:

  • 1 <= words.length <= 100
  • 1 <= words[i].length, pref.length <= 100
  • words[i]pref 由小写英文字母组成

解答

方法一:模拟

根据题意,对 words 的每个词判断前缀是否以 pref 开头即可。

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public int prefixCount(String[] words, String pref) {
int res = 0;
for (String word : words) {
if (word.startsWith(pref)) {
res++;
}
}
return res;
}
}
  • 时间复杂度\(O(NM)\),其中 Nwords 的长度, M 为最长单词的长度。

  • 空间复杂度\(O(1)\)

每题一图


LC 2185.Counting Words With a Given Prefix
https://chen-huaneng.github.io/2023/12/13/2023-12-13-2023-12-13-lc-2185/
作者
Abel
发布于
2023年12月13日
更新于
2023年12月13日
许可协议