Skip to content

← leetcode

Counting Words With a Given Prefix

· Easy

LeetCode problem 2185

Brute Force is the name of my favourite genre of leetcode questions?!

Literally just iterate through words and check if pref is the prefix to words[i]. I do not know what else there is to do here...

code

class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        int ans = 0;
        for (int i = 0; i < words.size(); ++i) {
            int counter = 0;
            for (int j = 0; j < pref.size(); ++j) {
                if (words[i][j] == pref[j]) {
                    ++counter;
                } else {
                    break;
                }
            }
            if (counter == pref.size()) {
                ++ans;
            }
        }
        return ans;
    }
};

complexity

  • Time: O(n)
  • Space: O(1)