[LeetCode] Count Prefixes of a Given String

2255. Count Prefixes of a Given String

You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters.

Return the number of strings in words that are a prefix of s.

A prefix of a string is a substring that occurs at the beginning of the string. A substring is a contiguous sequence of characters within a string.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int countPrefixes(vector<string>& words, string s) {
int res = 0;
for(auto& w : words) {
if(w.length() > s.length()) continue;
bool eq = true;
for(int i = 0; i < w.length() and eq; i++) {
if(s[i] != w[i]) eq = false;
}
res += eq;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/01/PS/LeetCode/count-prefixes-of-a-given-string/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.