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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

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.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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�...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
