Problem
A word is a run of non-space characters. Count the words in text; there may be extra spaces at the start, end or between words.
Implement count_words(text).
Input
text: The text to count.
Output
Return the number of words.
Constraints
0 ≤ length ≤ 10,000
Examples
Input:
text = "Learn to code today"
Expected output:
expected = 4
Input:
std::string text = "Learn to code today";
Expected output:
long long expected = 4;
Input:
string text = "Learn to code today";
Expected output:
long expected = 4;
Explanation
Four words separated by spaces: 4.
Input:
text = " "
Expected output:
expected = 0
Input:
std::string text = " ";
Expected output:
long long expected = 0;
Input:
string text = " ";
Expected output:
long expected = 0;
Explanation
Only spaces, so there are no words: 0.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
A word is any consecutive stretch of non-space characters.
Hint 2
Scan through the text and count transitions from spaces into letters.
Hint 3
Be careful with leading, trailing, and repeated spaces so you do not count empty runs.
Expected complexity
O(n) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.