{x}
blog image

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

Solution Explanation for "Number of Segments in a String"

This problem asks to count the number of segments in a string, where a segment is defined as a contiguous sequence of non-space characters. Two solutions are presented below, each with a different approach and complexity analysis.

Solution 1: Using split()

This solution leverages the built-in split() function (or its equivalent in other languages) to directly obtain the segments. It then iterates through the resulting array, counting only the non-empty segments.

Approach:

  1. Split the string: The input string s is split into an array of substrings using the space character as a delimiter. This is done using s.split() in Python, s.split(" ") in Java and Go, and explode(' ', $s) in PHP. istringstream is used in C++ to achieve similar functionality.

  2. Count non-empty segments: The code iterates through the array of substrings. Each substring that is not empty represents a segment. The count of these non-empty substrings is the answer.

Code (Python):

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

Complexity Analysis:

  • Time Complexity: O(N), where N is the length of the string. This is because the split() operation takes linear time in the worst case, and iterating through the resulting array also takes linear time. However, in most implementations, the time complexity of split is O(k*N), where k is the number of delimiters, which can still be considered linear in the average case.
  • Space Complexity: O(N) in the worst case, as the split() operation might create an array of size proportional to the length of the string (when there are many segments).

Solution 2: Iterating and Counting

This solution iterates through the string character by character, identifying the start of each segment and incrementing a counter.

Approach:

  1. Iterate through the string: The code iterates through the string s using a for loop.

  2. Identify segment starts: For each character c, it checks if c is not a space and if it's either the first character of the string or the preceding character was a space. If both conditions are true, it signifies the beginning of a new segment.

  3. Increment counter: If a new segment is found, the counter ans is incremented.

Code (Python):

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 Analysis:

  • Time Complexity: O(N), where N is the length of the string. The code iterates through the string once.
  • Space Complexity: O(1). The solution uses only a constant amount of extra space to store the counter ans.

Conclusion:

Both solutions have a time complexity of O(N). Solution 1 is potentially less efficient in space complexity in the worst-case scenario, whereas Solution 2 guarantees O(1) space complexity. The choice between the two depends on whether readability and conciseness (Solution 1) or guaranteed minimal space usage (Solution 2) is prioritized. However, in practice, the difference is usually negligible for strings of reasonable length.