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.
Restricciones
0 ≤ length ≤ 10,000
Ejemplos
Entrada:
text = "I love programming"
Salida esperada:
expected = "programming"
Entrada:
std::string text = "I love programming";
Salida esperada:
std::string expected = "programming";
Entrada:
string text = "I love programming";
Salida esperada:
string expected = "programming";
Explicación
"programming" has 11 letters, more than the others.
Entrada:
text = "cat dog cow"
Salida esperada:
expected = "cat"
Entrada:
std::string text = "cat dog cow";
Salida esperada:
std::string expected = "cat";
Entrada:
string text = "cat dog cow";
Salida esperada:
string expected = "cat";
Explicación
All are 3 letters; the first, "cat", wins.
Cómo abordarlo
Inténtalo primero por tu cuenta y luego abre las pistas una a una.
Pista 1
Compare words by length while scanning the text once.
Pista 2
Keep the first word seen with the maximum length so ties stay in order.
Pista 3
Handle the case where the text has no words at all.
Complejidad esperada
O(n) time, O(1) extra space
Referencias
Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.