LeetCode 题解工作台

判别首字母缩略词

给你一个字符串数组 words 和一个字符串 s ,请你判断 s 是不是 words 的 首字母缩略词 。 如果可以按顺序串联 words 中每个字符串的第一个字符形成字符串 s ,则认为 s 是 words 的首字母缩略词。例如, "ab" 可以由 ["apple", "banana"] 形成,但…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·string

bolt

答案摘要

我们可以遍历数组 中的每个字符串,将其首字母拼接起来,得到一个新的字符串 ,然后判断 是否等于 即可。 时间复杂度 ,空间复杂度 。其中 是数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串数组 words 和一个字符串 s ,请你判断 s 是不是 words首字母缩略词

如果可以按顺序串联 words 中每个字符串的第一个字符形成字符串 s ,则认为 swords 的首字母缩略词。例如,"ab" 可以由 ["apple", "banana"] 形成,但是无法从 ["bear", "aardvark"] 形成。

如果 swords 的首字母缩略词,返回 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 <= 100
  • 1 <= words[i].length <= 10
  • 1 <= s.length <= 100
  • words[i]s 由小写英文字母组成
lightbulb

解题思路

方法一:模拟

我们可以遍历数组 wordswords 中的每个字符串,将其首字母拼接起来,得到一个新的字符串 tt,然后判断 tt 是否等于 ss 即可。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是数组 wordswords 的长度。

1
2
3
4
class Solution:
    def isAcronym(self, words: List[str], s: str) -> bool:
        return "".join(w[0] for w in words) == s
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

判别首字母缩略词题解:数组·string | LeetCode #2828 简单