您当前的位置: 首页 >  liyatjj leetcode

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

liyatjj 发布时间:2022-05-22 09:01:44 ,浏览量:3

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

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

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

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

示例 1:

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

遍历字符串数组,然后与给出的字符串进行比较,在这里就需要注意,如果给出的字符串的长度比字符串数组里面的元素的长度长,就肯定不能匹配成功。 利用substring方法来截取字符串。 用equals方法比较两个字符串是否相等。 判断的时候,截取的长度应该和所给字符串长度一致,这样才能判断是否是前缀。

class Solution {
    public int prefixCount(String[] words, String pref) {
        int sum=0;
        for(String s:words){
            if(s.length()>=pref.length()){
            if(pref.equals(s.substring(0,pref.length()))){
                sum++;
            }
            }
        }
        return sum;
    }
}

substring方法: public String substring(int beginIndex):截取索引为beginIndex开始,一直到末尾的字符串。 public String substring(int beginIndex, int endIndex):截取从beginIndex开始,长度为endIndex-beginIndex的字符串。即索引从beginIndex开始,到endIndex-1结束。

关注
打赏
1688896170
查看更多评论

liyatjj

暂无认证

  • 3浏览

    0关注

    99博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.2405s