Leetcode Problem:
Summary
- Find the number of strings in the array that contain a given prefix.
Approach
- The solution uses a simple loop to iterate over each word in the array
- For each word, it checks if the prefix is present by comparing characters one by one
- If the prefix is found, it increments the answer counter.
Complexity
- O(n*m) where n is the number of words and m is the length of the prefix.
Explanation
- The solution works by iterating over each word in the array and comparing it with the prefix
- It uses two nested loops to compare characters one by one
- The outer loop iterates over each word, and the inner loop compares characters up to the length of the prefix
- If the prefix is found, it increments the answer counter.
Solution Code:
class Solution {
public:
int prefixCount(vector& words, string pref) {
int ans = 0;
for(string word : words){
int i = 0;
for( ; i < pref.size(); i++){
if(pref[i] != word[i]){
break;
}
}
if(i == pref.size()){
ans++;
}
}
return ans;
}
};
'알고리즘' 카테고리의 다른 글
Construct K Palindrome Strings (0) | 2025.03.04 |
---|---|
Word Subsets (0) | 2025.03.04 |
Count Prefix and Suffix Pairs I (0) | 2025.03.04 |
String Matching in an Array (0) | 2025.03.04 |
Minimum Number of Operations to Move All Balls to Each Box (0) | 2025.03.04 |