Leetcode 2255: Count Prefixes of a Given String

grid47
grid47
Exploring patterns and algorithms
Mar 26, 2024 5 min read

Given a list of strings words and a target string s, count how many strings in words are prefixes of s. A prefix is defined as a substring starting from the beginning of a string and extending up to a given length. Note that duplicate strings in words should be counted separately.
Problem
Approach
Steps
Complexity
Input: The input consists of a string array `words` and a single string `s`.
Example: words = ["cat", "ca", "dog", "c"], s = "catapult"
Constraints:
• 1 <= words.length <= 1000
• 1 <= words[i].length, s.length <= 10
• All strings in `words` and `s` consist of lowercase English letters.
Output: Return the count of strings in `words` that are prefixes of the string `s`.
Example: Output: 3
Constraints:
Goal: Determine how many strings in `words` match the prefix of `s` up to their length.
Steps:
• Iterate through each string in `words`.
• Check if the length of the current string is less than or equal to `s`.
• Compare each character of the string with the corresponding character in `s`.
• If all characters match, increment the count.
• Return the total count of matches.
Goal: Ensure that only valid prefixes of `s` are counted.
Steps:
• Strings in `words` can be shorter than `s`, but not longer.
• The comparison must stop as soon as a mismatch is found.
Assumptions:
• Strings in `words` and `s` are non-empty.
• Duplicate strings in `words` contribute to the count separately.
Input: words = ["car", "ca", "dog", "c"], s = "caravan"
Explanation: The strings in `words` which are prefixes of `s` are "car", "ca", and "c". Thus, the result is 3.

Input: words = ["x", "xy", "xyz"], s = "abcdef"
Explanation: None of the strings in `words` are prefixes of `s`. Thus, the result is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus