C# - count number of word starts O(n)


  • 0

    Increment the count on the first character of each word.

        public int CountSegments(string s) 
        {
            if (s.Length == 0) return 0;
            int count = s[0] != ' ' ? 1 : 0;
            for (int i = 1; i < s.Length; i++)
            {
                // count the number of word starts
                count += s[i] != ' ' && s[i-1] == ' ' ? 1 : 0;  
            }
            return count;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.