统计包含给定前缀的字符串
给你一个字符串数组 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结束。