Number of Segments in a String (LeetCode #434)
Alex Sikorski

Alex Sikorski

Jun 02, 2022

Number of Segments in a String (LeetCode #434)

#leetcode easy

#leetcode

#java

The problem starts by telling us that, 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.

It provides us with the following 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

The constraints are:

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

Breakdown

A for loop will be required for this task, as we can obtain characters at specified indexes. Whilst going through the string s, we will have to look out for specific conditions that determine a segment.

When looking at the input "Hello, my name is John", we will need to look out for two characters. A ' ' character and any other character declared in the constraints. For example, for the word substring " name", we can detect a segment as the character prior to 'n' is a space character: ' '.

If you apply this logic throughout the example input and count the segments, you will notice that we have only accounted for 4 segments even though there are 5. This is because the first substring, "Hello," does not have a ' ' at the start.

To counter this, all we have to do is check if the first index is not an ' ' character. If it isn't, we can simply add 1 to our segment count. This also covers our edge cases, such as input "A" or input " " where the length is just 1.

Solution

class Solution {
    public int countSegments(String s) {
        int res = 0;
        
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) !=' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
                res++;
            }   
        }
        return res;
    }
}

Result

2022-06-02 11_56_49-Number of Segments in a String - LeetCode — Mozilla Firefox.png

Alex Sikorski

Alex Sikorski

Currently working as a full stack Software Engineer and curiously seeking new knowledge in free time.

Leave a comment

Categories