Fácil 0 resueltos 0% de aceptación

Longest Word

Find the longest word in a sentence.

Lo que aprenderás

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

Problema

Ver traducción

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

Ejemplo 1
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.

Ejemplo 2
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.

Clasificación

Clasificación completa

La mejor solución aprobada de cada programador. Las más rápidas, ligeras y mejor valoradas van primero.

Aún no hay soluciones aprobadas. Resuélvelo y quédate el primer puesto.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.