Условие
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.
Ограничения
0 ≤ length ≤ 10,000
Примеры
Ввод:
text = "Learn to code today"
Ожидаемый вывод:
expected = 4
Ввод:
std::string text = "Learn to code today";
Ожидаемый вывод:
long long expected = 4;
Ввод:
string text = "Learn to code today";
Ожидаемый вывод:
long expected = 4;
Пояснение
Four words separated by spaces: 4.
Ввод:
text = " "
Ожидаемый вывод:
expected = 0
Ввод:
std::string text = " ";
Ожидаемый вывод:
long long expected = 0;
Ввод:
string text = " ";
Ожидаемый вывод:
long expected = 0;
Пояснение
Only spaces, so there are no words: 0.
Как подступиться
Сначала попробуйте сами, затем открывайте подсказки по одной.
Подсказка 1
A word is any consecutive stretch of non-space characters.
Подсказка 2
Scan through the text and count transitions from spaces into letters.
Подсказка 3
Be careful with leading, trailing, and repeated spaces so you do not count empty runs.
Ожидаемая сложность
O(n) time, O(1) extra space
Ссылки
Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.