Algorithm


Problem Name: 434. Number of Segments in a String

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 ' '.

Code Examples

#1 Code Example with Java Programming

Code - Java Programming


class Solution {
  public int countSegments(String s) {
    int count = 0;
    for (int i = 0; i  <  s.length(); i++) {
      if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
        count++;
      }
    }
    return count;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "Hello, my name is John"

Output

x
+
cmd
5

#2 Code Example with Javascript Programming

Code - Javascript Programming


const countSegments = function(s) {
    if(s.trim() === '') return 0
    return s.trim().split(' ').filter(el => el !== '').length
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "Hello, my name is John"

Output

x
+
cmd
5

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.split())
        
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "Hello"

Output

x
+
cmd
1

#4 Code Example with C# Programming

Code - C# Programming


using System;

namespace LeetCode
{
    public class _0434_NumberOfSegmentsInAString
    {
        public int CountSegments(string s)
        {
            return s.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
s = "Hello"

Output

x
+
cmd
1
Advertisements

Demonstration


Previous
#433 Leetcode Minimum Genetic Mutation Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#435 Leetcode Non-overlapping Intervals Solution in C, C++, Java, JavaScript, Python, C# Leetcode