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:
- Initialize a counter to 0.
- Iterate over each word in the list.
- For each word, use the
startswith
method to check if it’s a prefix of the string. - If it is, increment the counter.
- Return the counter.
Python solution:
|
|
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
.