Similar Problems

Similar Problems not available

Number Of Segments In A String - Leetcode Solution

Companies:

LeetCode:  Number Of Segments In A String Leetcode Solution

Difficulty: Easy

Topics: string  

Problem Statement:

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:

Input: s = "Hello, my name is John" Output: 5 Explanation: The five segments are "Hello,", "my", "name", "is", and "John".

Input: s = " Hello, my name is John " Output: 5

Approach:

Let's iterate through the given string and count the number of segments. Initially, we initialize the count as 0 and we traverse the entire string. If we encounter a non-space character, we check whether it's a new segment or not. If it is a new segment, we increment the count.

For this, we need a flag variable inSegment, which will indicate whether we are currently in a segment or in space. We initialize this as false, indicating that we are initially in space. As we traverse the string, if we encounter a non-space character, we set the inSegment flag as true.

If we encounter a space character and the inSegment flag is true, we increment the count and set the inSegment flag to false to indicate that we have exited the current segment.

At the end, if the inSegment flag is true, we increment the count as there will be an additional segment after the last non-space character.

Solution:

class Solution { public int countSegments(String s) {

    int count = 0;
    boolean inSegment = false;

    for(int i=0;i<s.length();i++){
        char c = s.charAt(i);

        if(c != ' '){
            // If the current character is not a space, check if we are in a segment or not
            if(!inSegment){
                // If not, we have started a new segment
                inSegment = true;
            }
        } else {
            // If the current character is a space, check if we are in a segment or not
            if(inSegment){
                // If we are in a segment, end it and increment the count
                count++;
                inSegment = false;
            }
        }
    }

    // If we are still in a segment at the end of the string, increment the count
    if(inSegment){
        count++;
    }
    
    return count;
}

}

Time Complexity: O(n), where n is the length of the string.

Space Complexity: O(1), as we are not using any additional space other than a few variables.

Number Of Segments In A String Solution Code

1