Легко Решено: 0 Процент решений: 0%

Count Words

Count the words in a sentence.

Чему вы научитесь

  • Split text into words
  • Handle repeated and leading spaces
  • Count items in a list

Условие

Показать перевод

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

Примеры

Пример 1
Ввод:
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.

Пример 2
Ввод:
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. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.