Talentd
FleetCode

434. Number of Segments in a String

Easy37.6% acceptance3 companies

Given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

Constraints:

  • 0 <= s.length <= 300
  • s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
  • The only space character in s is ' '.

Asked at 3 companies

Topics

4:54
Still stuck?Read 4 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def countSegments(self, s: str) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
"Hello, my name is John"
Input
"Hello"
Your code is saved on this device.Solution