<code class="language-php"><?php /** * @param String[] $words * @param String $pref * @return Integer */ function countWordsWithPrefix($words, $pref) { $count = 0; foreach ($words as $word) { if (strpos($word, $pref) === 0) { $count++; } } return $count; } // Example Usage $words1 = ["pay", "attention", "practice", "attend"]; $pref1 = "at"; echo countWordsWithPrefix($words1, $pref1); // Output: 2 $words2 = ["leetcode", "win", "loops", "success"]; $pref2 = "code"; echo countWordsWithPrefix($words2, $pref2); // Output: 0 ?></code>
Difficulty: Easy
Topics: Array, String, String Matching
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
.
Example 1:
words
= ["pay","attention","practice","attend"], pref
= "at"Example 2:
words
= ["leetcode","win","loops","success"], pref
= "code"Constraints:
Improved Solution (using strpos):
The provided solution uses substr
which is less efficient than strpos
for this specific task. strpos
directly checks for the prefix at the beginning of the string, avoiding unnecessary substring creation.
This improved PHP solution uses strpos
:
<?php function countWordsWithPrefix(array $words, string $pref): int { $count = 0; foreach ($words as $word) { if (strpos($word, $pref) === 0) { // Check if pref is at the beginning (index 0) $count++; } } return $count; } ?> <p><strong>Time Complexity:</strong> O(n*m) in the worst case, where n is the number of words and m is the length of the prefix. However, on average, it will be faster than the original <code>substr
solution.Space Complexity: O(1) - Constant extra space is used.
This revised answer provides a more efficient solution and maintains the clarity of the explanation. The image remains unchanged as it's relevant to the problem statement.
The above is the detailed content of Counting Words With a Given Prefix. For more information, please follow other related articles on the PHP Chinese website!