Skip to content

2255. Count Prefixes of a Given String 👍

  • Time: $O(n|\texttt{s}|)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  int countPrefixes(vector<string>& words, string s) {
    return count_if(begin(words), end(words),
                    [&](const auto& word) { return s.find(word) == 0; });
  }
};
1
2
3
4
5
class Solution {
  public int countPrefixes(String[] words, String s) {
    return (int) Arrays.stream(words).filter(word -> s.startsWith(word)).count();
  }
}
1
2
3
class Solution:
  def countPrefixes(self, words: List[str], s: str) -> int:
    return sum(map(s.startswith, words))