Problema
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.
Restrições
0 ≤ length ≤ 10,000
Exemplos
Entrada:
text = "I love programming"
Saída esperada:
expected = "programming"
Entrada:
std::string text = "I love programming";
Saída esperada:
std::string expected = "programming";
Entrada:
string text = "I love programming";
Saída esperada:
string expected = "programming";
Explicação
"programming" has 11 letters, more than the others.
Entrada:
text = "cat dog cow"
Saída esperada:
expected = "cat"
Entrada:
std::string text = "cat dog cow";
Saída esperada:
std::string expected = "cat";
Entrada:
string text = "cat dog cow";
Saída esperada:
string expected = "cat";
Explicação
All are 3 letters; the first, "cat", wins.
Como abordar
Tente sozinho primeiro e depois abra uma dica de cada vez.
Dica 1
Compare words by length while scanning the text once.
Dica 2
Keep the first word seen with the maximum length so ties stay in order.
Dica 3
Handle the case where the text has no words at all.
Complexidade esperada
O(n) time, O(1) extra space
Referências
Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.