Count Prefixes of a Given String

We need to count how many words from the given list are prefixes of the input string. A prefix of a string is a substring that occurs at the beginning of the string. Python’s str.startswith(prefix) method can be useful here.

This method returns True if the string starts with the specified prefix, False otherwise.

We can solve this problem using the following steps:

  1. Initialize a counter to 0.
  2. Iterate over each word in the list.
  3. For each word, use the startswith method to check if it’s a prefix of the string.
  4. If it is, increment the counter.
  5. Return the counter.

Python solution:

1
2
3
4
5
6
7
class Solution:
    def countPrefixes(self, words: List[str], s: str) -> int:
        count = 0
        for word in words:
            if s.startswith(word):
                count += 1
        return count

In this function, we initialize count to 0. Then, we start a loop over each word in words. If s starts with the current word, we increment count. After checking all the words, we return count as the number of words that are prefixes of s.