Return the number of strings in words that contain pref as a prefix.
Input: words = ["pay","attention","practice","attend"], pref = "at"
Output: 2
Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".
Straightforward
- iterate the words array and compare each word with pref at pref's length
Time: O(n)
Space: o(1)
public int prefixCount(String[] words, String pref) {
int len = pref.length();
int ans = 0;
for (String word: words) {
if (word.length() >= len)
ans += word.substring(0, len).equals(pref) ? 1:0;
}
return ans;
}