Problem
You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.
Examples
Example 1:
| |
Example 2:
| |
Constraints
1 <= words.length <= 1001 <= words[i].length, pref.length <= 100words[i]andprefconsist of lowercase English letters.
Solution
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Using Starts with
Here is the approach:
- Create a counter
ansinitialized to 0. - Iterate through each string
wordinwords. - For each
word, check if it starts withprefusing thestartsWithmethod in Java and thestartswithmethod in Python. - If it does, increment the counter
ans. - Return the counter
ans.
Code
| |
| |
Complexity
- ⏰ Time complexity:
O(n * l), wherenis the number of words in the array, andlis the length of the longest word. This is because for each of thenwords, we may need to check up tomcharacters to verify if the word starts with the given prefix. - 🧺 Space complexity:
O(1)as we are using some variables here and there