LeetCode 题解工作台
判别首字母缩略词
给你一个字符串数组 words 和一个字符串 s ,请你判断 s 是不是 words 的 首字母缩略词 。 如果可以按顺序串联 words 中每个字符串的第一个字符形成字符串 s ,则认为 s 是 words 的首字母缩略词。例如, "ab" 可以由 ["apple", "banana"] 形成,但…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·string
答案摘要
我们可以遍历数组 中的每个字符串,将其首字母拼接起来,得到一个新的字符串 ,然后判断 是否等于 即可。 时间复杂度 ,空间复杂度 。其中 是数组 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个字符串数组 words 和一个字符串 s ,请你判断 s 是不是 words 的 首字母缩略词 。
如果可以按顺序串联 words 中每个字符串的第一个字符形成字符串 s ,则认为 s 是 words 的首字母缩略词。例如,"ab" 可以由 ["apple", "banana"] 形成,但是无法从 ["bear", "aardvark"] 形成。
如果 s 是 words 的首字母缩略词,返回 true ;否则,返回 false 。
示例 1:
输入:words = ["alice","bob","charlie"], s = "abc" 输出:true 解释:words 中 "alice"、"bob" 和 "charlie" 的第一个字符分别是 'a'、'b' 和 'c'。因此,s = "abc" 是首字母缩略词。
示例 2:
输入:words = ["an","apple"], s = "a" 输出:false 解释:words 中 "an" 和 "apple" 的第一个字符分别是 'a' 和 'a'。 串联这些字符形成的首字母缩略词是 "aa" 。 因此,s = "a" 不是首字母缩略词。
示例 3:
输入:words = ["never","gonna","give","up","on","you"], s = "ngguoy" 输出:true 解释:串联数组 words 中每个字符串的第一个字符,得到字符串 "ngguoy" 。 因此,s = "ngguoy" 是首字母缩略词。
提示:
1 <= words.length <= 1001 <= words[i].length <= 101 <= s.length <= 100words[i]和s由小写英文字母组成
解题思路
方法一:模拟
我们可以遍历数组 中的每个字符串,将其首字母拼接起来,得到一个新的字符串 ,然后判断 是否等于 即可。
时间复杂度 ,空间复杂度 。其中 是数组 的长度。
class Solution:
def isAcronym(self, words: List[str], s: str) -> bool:
return "".join(w[0] for w in words) == s
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates the ability to manipulate arrays and strings efficiently.
- question_mark
Candidate should be able to recognize the problem's pattern as an acronym check.
- question_mark
Look for an understanding of early exit conditions to avoid unnecessary work.
常见陷阱
外企场景- error
Failing to check the lengths of `s` and `words` upfront, leading to unnecessary string building.
- error
Not handling edge cases like when `words` has only one word or when `s` is empty.
- error
Not considering the case where the acronym string is longer than `s`, causing unnecessary iterations.
进阶变体
外企场景- arrow_right_alt
Check if a string is an acronym using both uppercase and lowercase letters.
- arrow_right_alt
Implement a version that checks the acronym only for specific words in the list.
- arrow_right_alt
Optimize the solution for handling larger datasets efficiently.