Problema
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.
Vincoli
0 ≤ length ≤ 10,000
Esempi
Input:
text = "Learn to code today"
Output atteso:
expected = 4
Input:
std::string text = "Learn to code today";
Output atteso:
long long expected = 4;
Input:
string text = "Learn to code today";
Output atteso:
long expected = 4;
Spiegazione
Four words separated by spaces: 4.
Input:
text = " "
Output atteso:
expected = 0
Input:
std::string text = " ";
Output atteso:
long long expected = 0;
Input:
string text = " ";
Output atteso:
long expected = 0;
Spiegazione
Only spaces, so there are no words: 0.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
A word is any consecutive stretch of non-space characters.
Suggerimento 2
Scan through the text and count transitions from spaces into letters.
Suggerimento 3
Be careful with leading, trailing, and repeated spaces so you do not count empty runs.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.