Counting Words With a Given Prefix LeetCode solution in C++

1
// The easiest solution to this problem is:
2
// Step 1: Calculate length of "pref"
3
// Step 2: find substring of "words" from 0 to length of "pref"
4
// if both match increment count by 1;
5

6
class Solution {
7
public:
8
int prefixCount(vector<string> &words, string pref) {
9
int count = 0;
10
int preflen = pref.size(); // step 1
11

12
for (auto i : words) {
13
if (i.substr(0, preflen) == pref) // step 2
14
count++; // if both matches then increment count by 1
15
}
16
return count; // return count
17
}
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0