Facile 0 risolte 0% di accettazione

Count Words

Count the words in a sentence.

Cosa imparerai

  • Split text into words
  • Handle repeated and leading spaces
  • Count items in a list

Problema

Mostra traduzione

A word is a run of non-space characters. Count the words in text; there may be extra spaces at the start, end or between words.

Implement count_words(text).

Input

text: The text to count.

Output

Return the number of words.

Vincoli

0 ≤ length ≤ 10,000

Esempi

Esempio 1
Input:
text = "Learn to code today"

Output atteso:
expected = 4
Input:
std::string text = "Learn to code today";

Output atteso:
long long expected = 4;
Input:
string text = "Learn to code today";

Output atteso:
long expected = 4;

Spiegazione

Four words separated by spaces: 4.

Esempio 2
Input:
text = "   "

Output atteso:
expected = 0
Input:
std::string text = "   ";

Output atteso:
long long expected = 0;
Input:
string text = "   ";

Output atteso:
long expected = 0;

Spiegazione

Only spaces, so there are no words: 0.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

A word is any consecutive stretch of non-space characters.

Suggerimento 2

Scan through the text and count transitions from spaces into letters.

Suggerimento 3

Be careful with leading, trailing, and repeated spaces so you do not count empty runs.

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.