Facile 0 résolus 0 % de réussite

Longest Word

Find the longest word in a sentence.

Ce que vous allez apprendre

  • Split a sentence into words
  • Track the longest word seen so far
  • Break ties by keeping the first one

Problème

Afficher la traduction

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.

Contraintes

0 ≤ length ≤ 10,000

Exemples

Exemple 1
Entrée :
text = "I love programming"

Sortie attendue :
expected = "programming"
Entrée :
std::string text = "I love programming";

Sortie attendue :
std::string expected = "programming";
Entrée :
string text = "I love programming";

Sortie attendue :
string expected = "programming";

Explication

"programming" has 11 letters, more than the others.

Exemple 2
Entrée :
text = "cat dog cow"

Sortie attendue :
expected = "cat"
Entrée :
std::string text = "cat dog cow";

Sortie attendue :
std::string expected = "cat";
Entrée :
string text = "cat dog cow";

Sortie attendue :
string expected = "cat";

Explication

All are 3 letters; the first, "cat", wins.

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

Compare words by length while scanning the text once.

Indice 2

Keep the first word seen with the maximum length so ties stay in order.

Indice 3

Handle the case where the text has no words at all.

Complexité attendue

O(n) time, O(1) extra space

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.