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