Leetcode - Number of Segments in a String Solution
1 min read

Leetcode - Number of Segments in a String Solution

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:

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

Example 3:

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

Example 4:

Input: s = ""
Output: 0


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

Solution in Python

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

Enjoying these posts? Subscribe for more

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

That's okay. But without advertising-income, we can't keep making this site awesome.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add thepoorcoder.com to your ad blocking whitelist or disable your adblocking software.