LeetCode 题解工作台
统计是给定字符串前缀的字符串数目
给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。 请你返回 words 中是字符串 s 前缀 的 字符串数目 。 一个字符串的 前缀 是出现在字符串开头的子字符串。 子字符串 是一个字符串中的连续一段字符序列。 示例 1: 输入: word…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们直接遍历数组 ,对于每个字符串 ,判断 是否以 为前缀,如果是则答案加一。 遍历结束后,返回答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个字符串数组 words 和一个字符串 s ,其中 words[i] 和 s 只包含 小写英文字母 。
请你返回 words 中是字符串 s 前缀 的 字符串数目 。
一个字符串的 前缀 是出现在字符串开头的子字符串。子字符串 是一个字符串中的连续一段字符序列。
示例 1:
输入:words = ["a","b","c","ab","bc","abc"], s = "abc" 输出:3 解释: words 中是 s = "abc" 前缀的字符串为: "a" ,"ab" 和 "abc" 。 所以 words 中是字符串 s 前缀的字符串数目为 3 。
示例 2:
输入:words = ["a","a"], s = "aa" 输出:2 解释: 两个字符串都是 s 的前缀。 注意,相同的字符串可能在 words 中出现多次,它们应该被计数多次。
提示:
1 <= words.length <= 10001 <= words[i].length, s.length <= 10words[i]和s只 包含小写英文字母。
解题思路
方法一:遍历计数
我们直接遍历数组 ,对于每个字符串 ,判断 是否以 为前缀,如果是则答案加一。
遍历结束后,返回答案即可。
时间复杂度 ,其中 和 分别是数组 的长度和字符串 的长度。空间复杂度 。
class Solution:
def countPrefixes(self, words: List[str], s: str) -> int:
return sum(s.startswith(w) for w in words)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate is expected to demonstrate familiarity with string manipulation techniques.
- question_mark
Efficiency in handling edge cases such as duplicate words should be discussed.
- question_mark
Candidates may be expected to propose optimizations or alternative solutions for larger input sizes.
常见陷阱
外企场景- error
Forgetting to count duplicate words in the list.
- error
Overcomplicating the solution by using complex algorithms for a simple problem.
- error
Neglecting to account for edge cases such as an empty list or a word being exactly the same as `s`.
进阶变体
外企场景- arrow_right_alt
Instead of using the `startswith` method, implement a manual comparison of the beginning substring.
- arrow_right_alt
Consider a case where the list of words is very large, and explore optimized approaches like sorting or hashing.
- arrow_right_alt
Extend the problem to check for prefixes of multiple target strings, not just one.