Problème
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.
Contraintes
0 ≤ length ≤ 10,000
Exemples
Entrée :
text = "Learn to code today"
Sortie attendue :
expected = 4
Entrée :
std::string text = "Learn to code today";
Sortie attendue :
long long expected = 4;
Entrée :
string text = "Learn to code today";
Sortie attendue :
long expected = 4;
Explication
Four words separated by spaces: 4.
Entrée :
text = " "
Sortie attendue :
expected = 0
Entrée :
std::string text = " ";
Sortie attendue :
long long expected = 0;
Entrée :
string text = " ";
Sortie attendue :
long expected = 0;
Explication
Only spaces, so there are no words: 0.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
A word is any consecutive stretch of non-space characters.
Indice 2
Scan through the text and count transitions from spaces into letters.
Indice 3
Be careful with leading, trailing, and repeated spaces so you do not count empty runs.
Complexité attendue
O(n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.