2185. Counting Words With a Given Prefix #1108
-
|
Topics: You are given an array of strings Return the number of strings in A prefix of a string Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We can iterate through the Let's implement this solution in PHP: 2185. Counting Words With a Given Prefix <?php
/**
* @param String[] $words
* @param String $pref
* @return Integer
*/
function countWordsWithPrefix($words, $pref) {
// Initialize count variable
$count = 0;
// Iterate through each word in the words array
foreach ($words as $word) {
// Check if the word starts with the prefix using substr
if (substr($word, 0, strlen($pref)) === $pref) {
// Increment count if the word contains the prefix
$count++;
}
}
// Return the final 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
?>Explanation:
Time Complexity:
This solution is efficient for the input constraints. |
Beta Was this translation helpful? Give feedback.
We can iterate through the
wordsarray and check if the givenprefis a prefix of each word. You can use thesubstrfunction to check the beginning part of each string and compare it withpref. If they match, you increment the count.Let's implement this solution in PHP: 2185. Counting Words With a Given Prefix