Leetcode

Counting Words With a Given Prefix

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

C++

class Solution {
 public:
  int prefixCount(vector<string>& words, string pref) {
    return count_if(begin(words), end(words),
                    [&](const auto& word) { return word.find(pref) == 0; });
  }
};

JAVA

class Solution {
  public int prefixCount(String[] words, String pref) {
    return (int) Arrays.stream(words).filter(w -> w.startsWith(pref)).count();
  }
}

Python

class Solution:
  def prefixCount(self, words: List[str], pref: str) -> int:
    return sum(word.startswith(pref) for word in words)