统计包含给定前缀的字符串【LC2185】
You are given an array of strings
words
and a stringpref
.Return the number of strings in
words
that containpref
as a prefix.A prefix of a string
s
is any leading contiguous substring ofs
.
有点玩累啦 开始好好学习吧 尽量白天学完
-
思路:判断每一个
word
是否以prefix
开头,最后返回满足条件的单词数量。 -
实现
word.startsWith(pref)
word.indexOf(pref) == 0
word.length() >= m && word.substring(0, m).equals(pref)
class Solution { public int prefixCount(String[] words, String pref) { int res = 0, m = pref.length(); for (String word : words){ if (word.startsWith(pref)){ res++; } // if (word.indexOf(pref) == 0){ // res++; // } // if (word.length() >= m && word.substring(0, m).equals(pref)){ // res++; // } } return res; } }
- 复杂度
- 时间复杂度:
O
(
n
m
)
O(nm)
O(nm),
n
n
n为
words
数组的长度, m m m为prefix
前缀的长度 - 空间复杂度: O ( n ) O(n) O(n)
- 时间复杂度:
O
(
n
m
)
O(nm)
O(nm),
n
n
n为