2185. Counting Words With a Given Prefix
2185. Counting Words With a Given Prefix
[Problem]
Intuition
- Brute Force works because constraints are small.
1
2
3
Constraints
1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
Approach
- For each word in
words
check if it haspref
as prefix prefix.
Complexity Analysis
- Time Complexity: O(n)
n
: size ofwords
array.
- Space Complexity: O(1)
- No extra space used.
Code
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int prefixCount(String[] words, String pref) {
int cnt = 0;
for(String str : words){
// `str` contains `pref` as prefix
if(str.startsWith(pref)){
cnt += 1; // increment cnt
}
}
return cnt;
}
}
This post is licensed under CC BY 4.0 by the author.