LeetCode 题解工作台

字符串中的单词数

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。 示例: 输入: "Hello, my name is John" 输出: 5 解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们将字符串 按照空格进行分割,然后统计不为空的单词个数。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

请注意,你可以假定字符串里不包括任何不可打印的字符。

示例:

输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
lightbulb

解题思路

方法一:字符串分割

我们将字符串 s\textit{s} 按照空格进行分割,然后统计不为空的单词个数。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 s\textit{s} 的长度。

1
2
3
4
class Solution:
    def countSegments(self, s: str) -> int:
        return len(s.split())
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Candidate demonstrates a clear understanding of how to handle spaces and non-space characters in the string.

  • question_mark

    Candidate uses an efficient strategy to avoid unnecessary operations, such as splitting on all spaces.

  • question_mark

    Candidate can explain how to optimize for edge cases, such as leading, trailing, or multiple spaces.

warning

常见陷阱

外企场景
  • error

    Not handling leading or trailing spaces correctly, which might lead to inaccurate segment counts.

  • error

    Forgetting to exclude empty segments when splitting the string, especially when multiple spaces are used.

  • error

    Using inefficient methods like repeatedly scanning the string for spaces instead of processing the string in a single pass.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    The input string contains leading or trailing spaces.

  • arrow_right_alt

    The input string contains multiple consecutive spaces.

  • arrow_right_alt

    The input string is empty or consists only of spaces.

help

常见问题

外企场景

字符串中的单词数题解:String-driven solution … | LeetCode #434 简单