Einfach 0 gelöst 0% Erfolgsquote

Count Words

Count the words in a sentence.

Das lernst du

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

Problem

Übersetzung anzeigen

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.

Einschränkungen

0 ≤ length ≤ 10,000

Beispiele

Beispiel 1
Eingabe:
text = "Learn to code today"

Erwartete Ausgabe:
expected = 4
Eingabe:
std::string text = "Learn to code today";

Erwartete Ausgabe:
long long expected = 4;
Eingabe:
string text = "Learn to code today";

Erwartete Ausgabe:
long expected = 4;

Erläuterung

Four words separated by spaces: 4.

Beispiel 2
Eingabe:
text = "   "

Erwartete Ausgabe:
expected = 0
Eingabe:
std::string text = "   ";

Erwartete Ausgabe:
long long expected = 0;
Eingabe:
string text = "   ";

Erwartete Ausgabe:
long expected = 0;

Erläuterung

Only spaces, so there are no words: 0.

So gehst du vor

Versuch es zuerst allein und öffne dann einen Hinweis nach dem anderen.

Hinweis 1

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

Hinweis 2

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

Hinweis 3

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

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.

Die beste bestandene Lösung jedes Coders. Schnellere, sparsamere und besser bewertete Lösungen stehen weiter oben.

Noch keine bestandene Lösung. Löse sie und hol dir Platz eins.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.