前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 6008. 统计包含给定前缀的字符串

LeetCode 6008. 统计包含给定前缀的字符串

作者头像
Michael阿明
发布2022-03-10 18:41:06
3530
发布2022-03-10 18:41:06
举报

文章目录

1. 题目

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

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

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

代码语言:javascript
复制
示例 1:
输入:words = ["pay","attention","practice","attend"], pref = "at"
输出:2
解释:以 "at" 作为前缀的字符串有两个,分别是:"attention" 和 "attend" 。

示例 2:
输入:words = ["leetcode","win","loops","success"], pref = "code"
输出:0
解释:不存在以 "code" 作为前缀的字符串。
 
提示:
1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
words[i] 和 pref 由小写英文字母组成

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/counting-words-with-a-given-prefix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

代码语言:javascript
复制
class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        return len([x for x in words if x.startswith(pref)])

36 ms 15.1 MB Python3

代码语言:javascript
复制
class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        int n = pref.size(), ans = 0;
        for(auto& w : words)
        {
            if(w.size() < n) continue;
            if(w.substr(0,n) == pref)
                ans++;
        }
        return ans;
    }
};

12 ms 9.7 MB C++


我的CSDN博客地址 https://michael.blog.csdn.net/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档