Skip to content
the poor coder

Leetcode - Number of Segments in a String Solution

Poor Man
Published
Updated
Reading time
1 min read

You are 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:

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

Example 2:

Text
Input: s = "Hello"
Output: 1

Example 3:

Text
Input: s = "love live! mu'sic forever"
Output: 4

Example 4:

Text
Input: s = ""
Output: 0

Constraints:

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

Solution in Python#

Python
class Solution:
    def countSegments(self, s: str) -> int:
        return len(s.split())

Keep going

2021

Leetcode - Camelcase Matching Solution

A query word matches a given pattern if we can insert lowercase letters to the pattern word so that it equals the query. (We may insert each character at any position, and may insert 0 characters.) Given a list of…

ESC