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.
Vincoli
0 ≤ length ≤ 10,000
Esempi
Input:
text = "I love programming"
Output atteso:
expected = "programming"
Input:
std::string text = "I love programming";
Output atteso:
std::string expected = "programming";
Input:
string text = "I love programming";
Output atteso:
string expected = "programming";
Spiegazione
"programming" has 11 letters, more than the others.
Input:
text = "cat dog cow"
Output atteso:
expected = "cat"
Input:
std::string text = "cat dog cow";
Output atteso:
std::string expected = "cat";
Input:
string text = "cat dog cow";
Output atteso:
string expected = "cat";
Spiegazione
All are 3 letters; the first, "cat", wins.
Come affrontarlo
Prova prima da solo, poi apri un suggerimento alla volta.
Suggerimento 1
Compare words by length while scanning the text once.
Suggerimento 2
Keep the first word seen with the maximum length so ties stay in order.
Suggerimento 3
Handle the case where the text has no words at all.
Complessità attesa
O(n) time, O(1) extra space
Riferimenti
Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.