统计包含给定前缀的字符串【LC2185】
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
有点玩累啦 开始好好学习吧 尽量白天学完
- 思路:判断每一个word是否以prefix开头,最后返回满足条件的单词数量。
- 实现
。word.startsWith(pref)
。word.indexOf(pref) == 0
。word.length() >= m && word.substring(0, m).equals(pref)
class Solution { public int prefixCount(String[] words, String pref) { int res = 0, m = pref.length(); for (String word : words){ if (word.startsWith(pref)){ res++; } // if (word.indexOf(pref) == 0){ // res++; // } // if (word.length() >= m && word.substring(0, m).equals(pref)){ // res++; // } } return res; } }
。复杂度
- 时间复杂度:O(nm),n为words数组的长度,m为prefix前缀的长度
- 空间复杂度:O ( n )