Tutte le sfide
Facile 0 risolte 0% di accettazione

Longest Word

Find the longest word in a sentence.

Cosa imparerai

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

Problema

Mostra traduzione

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

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

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

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.