[LeetCode] Counting Words With a Given Prefix

2185. Counting Words With a Given Prefix

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int res = 0;
for(auto w : words) {
if(w.length() < pref.length()) continue;
bool find = true;
for(int i = 0; i < pref.length() and find; i++) {
if(w[i] != pref[i]) find = false;
}
if(find) res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/27/PS/LeetCode/counting-words-with-a-given-prefix/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.