Counting Words With a Given Prefix
The problem is asking us to find the number of strings in a given array that have a specific prefix. We’ll iterate through the array and check the beginning of each string to see if it matches the given prefix. If it does, we’ll increment our counter.
Here’s the code:
|
|
Explanation
- We utilize the built-in
startswith
method, which checks if the given string starts with a specific prefix. - If the current word starts with the given prefix, we increment the count.
- We return the final count.
Example
For the input words = ["pay","attention","practice","attend"]
and pref = "at"
, the method would return 2
since the words “attention” and “attend” start with “at”.