Monday, January 18, 2021

Number of Segments in a String

Problem: 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 = "Hi, Nishant!"
Output: 2
Explanation: The two segments are ["Hi,", "Nishant!"]


Approach: It's a straight forward problem to solve. Just look at the implementation to understand the approach.


Implementation in C#:

    public int CountSegments(string s) 

    {    

        int charCount = 0, wordCount = 0; 

        for (int i = 0; i < s.Length; ++i)

        {

            charCount = s[i] == ' ' ? 0 : charCount + 1;

            if (charCount == 1)

            {

                ++wordCount;

            }

        }  

        return wordCount;

    }


Complexity: O(n)

No comments:

Post a Comment