Counting Words With a Given Prefix

easy string prefix

Problem

Given an array of strings words and a string pref, return the number of strings in words that begin with pref. A string s begins with pref when pref is a prefix of s, meaning the first characters of s match pref exactly.

Inputwords = ["pay", "attention", "practice", "attend"], pref = "at"
Output2
"attention" and "attend" both start with "at"; "pay" and "practice" do not.

def prefix_count(words, pref):
    count = 0
    for w in words:
        if w.startswith(pref):
            count += 1
    return count
function prefixCount(words, pref) {
  let count = 0;
  for (const w of words) {
    if (w.startsWith(pref)) {
      count++;
    }
  }
  return count;
}
class Solution {
    public int prefixCount(String[] words, String pref) {
        int count = 0;
        for (String w : words) {
            if (w.startsWith(pref)) {
                count++;
            }
        }
        return count;
    }
}
int prefixCount(vector<string>& words, string pref) {
    int count = 0;
    for (const string& w : words) {
        if (w.rfind(pref, 0) == 0) {
            count++;
        }
    }
    return count;
}
Time: O(n · m) Space: O(1)