Count Prefixes of a Given String

easy string

Problem

You are given a list of strings words and a string s. Return the number of strings in words that are a prefix of s. A prefix of s is a string that matches the first characters of s exactly.

Inputwords = ["a","b","c","ab","bc","abc"], s = "abc"
Output3
"a", "ab" and "abc" are prefixes of "abc".

def count_prefixes(words, s):
    count = 0
    for w in words:
        if s.startswith(w):
            count += 1
    return count
function countPrefixes(words, s) {
  let count = 0;
  for (const w of words) {
    if (s.startsWith(w)) {
      count++;
    }
  }
  return count;
}
class Solution {
    public int countPrefixes(String[] words, String s) {
        int count = 0;
        for (String w : words) {
            if (s.startsWith(w)) {
                count++;
            }
        }
        return count;
    }
}
int countPrefixes(vector<string>& words, string s) {
    int count = 0;
    for (const string& w : words) {
        if (s.rfind(w, 0) == 0) {
            count++;
        }
    }
    return count;
}
Time: O(total characters) Space: O(1)