方法一:模拟
思路与算法
遍历每个字符串,判断是否以 pref 为前缀。使用 startsWith 判断。
代码
class Solution {
public int prefixCount(String[] words, String pref) {
int ans = 0;
for (String w : words) {
if (w.startsWith(pref)) {
ans++;
}
}
return ans;
}
}
复杂度分析
时间复杂度:O(mn),m 是 pref 的长度,n 是 words 的长度
空间复杂度:O(1),常数空间