LeetCode 2185. 统计包含给定前缀的字符串
给你一个字符串数组 words 和一个字符串 pref 。
返回 words 中以 pref 作为 前缀 的字符串的数目。
字符串 s 的 前缀 就是 s 的任一前导连续字符串。
示例 1:
输入:words = [“pay”,“attention”,“practice”,“attend”], pref = “at”
输出:2
解释:以 “at” 作为前缀的字符串有两个,分别是:“attention” 和 “attend” 。
1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
words[i] 和 pref 由小写英文字母组成
直接遍历words,看其中每个元素是否包含指定前缀:
class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int ret = 0;
for (string &word : words) {
if (word.size() < pref.size()) {
continue;
}
bool flag = 1;
for (int i = 0; i < pref.size(); ++i) {
if (word[i] != pref[i]) {
flag = 0;
}
}
ret += flag;
}
return ret;
}
};
如果words的大小为n,pref的长度为m,此算法时间复杂度为O(n*m),空间复杂度为O(1)。
也可直接用string的compare方法:
class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int ret = 0;
for (string &word : words) {
if (!word.compare(0, pref.size(), pref)) {
++ret;
}
}
return ret;
}
};
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)