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

Longest Word

Find the longest word in a sentence.

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

  • Split a sentence into words
  • Track the longest word seen so far
  • Break ties by keeping the first one

Условие

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

Return the longest word in text (words are separated by spaces). If several words share the longest length, return the first one.

Implement longest_word(text).

Input

text: The sentence.

Output

Return the longest word, or an empty string if there are no words.

Ограничения

0 ≤ length ≤ 10,000

Примеры

Пример 1
Ввод:
text = "I love programming"

Ожидаемый вывод:
expected = "programming"
Ввод:
std::string text = "I love programming";

Ожидаемый вывод:
std::string expected = "programming";
Ввод:
string text = "I love programming";

Ожидаемый вывод:
string expected = "programming";

Пояснение

"programming" has 11 letters, more than the others.

Пример 2
Ввод:
text = "cat dog cow"

Ожидаемый вывод:
expected = "cat"
Ввод:
std::string text = "cat dog cow";

Ожидаемый вывод:
std::string expected = "cat";
Ввод:
string text = "cat dog cow";

Ожидаемый вывод:
string expected = "cat";

Пояснение

All are 3 letters; the first, "cat", wins.

Как подступиться

Сначала попробуйте сами, затем открывайте подсказки по одной.

Подсказка 1

Compare words by length while scanning the text once.

Подсказка 2

Keep the first word seen with the maximum length so ties stay in order.

Подсказка 3

Handle the case where the text has no words at all.

Ожидаемая сложность

O(n) time, O(1) extra space

Ссылки

Это задание адаптировано для CodeUtility. Следуйте условию и ограничениям выше.

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

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

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

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

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