알고리즘

Counting Words With a Given Prefix

짬뽕얼큰하게 2025. 3. 4. 08:50

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;
    }
};