Problem
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.
Einschränkungen
0 ≤ length ≤ 10,000
Beispiele
Eingabe:
text = "I love programming"
Erwartete Ausgabe:
expected = "programming"
Eingabe:
std::string text = "I love programming";
Erwartete Ausgabe:
std::string expected = "programming";
Eingabe:
string text = "I love programming";
Erwartete Ausgabe:
string expected = "programming";
Erläuterung
"programming" has 11 letters, more than the others.
Eingabe:
text = "cat dog cow"
Erwartete Ausgabe:
expected = "cat"
Eingabe:
std::string text = "cat dog cow";
Erwartete Ausgabe:
std::string expected = "cat";
Eingabe:
string text = "cat dog cow";
Erwartete Ausgabe:
string expected = "cat";
Erläuterung
All are 3 letters; the first, "cat", wins.
So gehst du vor
Versuch es zuerst allein und öffne dann einen Hinweis nach dem anderen.
Hinweis 1
Compare words by length while scanning the text once.
Hinweis 2
Keep the first word seen with the maximum length so ties stay in order.
Hinweis 3
Handle the case where the text has no words at all.
Erwartete Komplexität
O(n) time, O(1) extra space
Referenzen
Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.