Counting Words With a Given Prefix
<?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 ?>
- Counting Words With a Given Prefix
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:
- Input:
words
= ["pay","attention","practice","attend"],pref
= "at" - Output: 2
- Explanation: The 2 strings that contain "at" as a prefix are: "attention" and "attend".
Example 2:
- Input:
words
= ["leetcode","win","loops","success"],pref
= "code" - Output: 0
- Explanation: There are no strings that contain "code" as a prefix.
Constraints:
- 1 <= words.length <= 100
- 1 <= words[i].length <= 20
- 1 <= pref.length <= 20
- words[i] and pref consist of lowercase English letters.
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; } ?>
Time Complexity: 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 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
