Problem

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

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

Examples

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

Solution

Method 1 - Split and count

Here is the approach:

1. Splitting the String:

  • The input string s is split using the split(" ") method. This splits the string by spaces and returns an array of substrings.
    • For example, if s = "Hello, my name is John", the result of s.split(" ") would be ["Hello,", "my", "name", "is", "John"].

2. Iterating through the Split Portions:

  • The code iterates through each substring (referred to as t) in the array resulting from the split operation.

3. Counting Non-Empty Substrings:

  • For each substring t, the code checks if it is not an empty string (!"".equals(t)).
    • This is necessary because split(" ") creates empty strings for consecutive spaces in the input.
    • For instance, if s = "Hello John", the result of s.split(" ") would be ["Hello", "", "", "John"].

4. Incrementing the Segment Count:

  • If a substring is not empty, the result counter res is incremented. This counter keeps track of the number of segments.

5. Returning the Result:

  • Finally, the method returns the count of segments which is stored in res.

Code

Java
class Solution {
    public int countSegments(String s) {
        int res = 0;
        for (String t : s.split(" ")) {
            if (!"".equals(t)) {
                ++res;
            }
        }
        return res;
    }
}
class Solution {
    public int countSegments(String s) {
        int ans = 0;
        for (String t : s.split(" ")) {
            if (!"".equals(t)) {
                ++ans;
            }
        }
        return ans;
    }
}
C++
class Solution {
public:
    int countSegments(string s) {
        int ans = 0;
        istringstream ss(s);
        while (ss >> s) ++ans;
        return ans;
    }
};
class Solution {
public:
    int countSegments(string s) {
        int ans = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
                ++ans;
            }
        }
        return ans;
    }
};
Go
func countSegments(s string) int {
	ans := 0
	for _, t := range strings.Split(s, " ") {
		if len(t) > 0 {
			ans++
		}
	}
	return ans
}
func countSegments(s string) int {
	ans := 0
	for i, c := range s {
		if c != ' ' && (i == 0 || s[i-1] == ' ') {
			ans++
		}
	}
	return ans
}
PHP
class Solution {
    /**
     * @param String $s
     * @return Integer
     */
    function countSegments($s) {
        $arr = explode(' ', $s);
        $cnt = 0;
        for ($i = 0; $i < count($arr); $i++) {
            if (strlen($arr[$i]) != 0) {
                $cnt++;
            }
        }
        return $cnt;
    }
}
Python
class Solution:
    def countSegments(self, s: str) -> int:
        return len(s.split())
class Solution:
    def countSegments(self, s: str) -> int:
        ans = 0
        for i, c in enumerate(s):
            if c != ' ' and (i == 0 or s[i - 1] == ' '):
                ans += 1
        return ans

Complexity

  • Time: O(n),  where n is the length of the string s.
  • Space: O(n), because splitting the string creates an array of substrings, and in the worst case, where there are no spaces in the string, this array will hold n characters divided into substrings.