簡単 0件解決済み 正答率0%

Count Words

Count the words in a sentence.

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

0 ≤ length ≤ 10,000

例

例 1
入力:
text = "Learn to code today"

期待される出力:
expected = 4
入力:
std::string text = "Learn to code today";

期待される出力:
long long expected = 4;
入力:
string text = "Learn to code today";

期待される出力:
long expected = 4;

解説

Four words separated by spaces: 4.

例 2
入力:
text = "   "

期待される出力:
expected = 0
入力:
std::string text = "   ";

期待される出力:
long long expected = 0;
入力:
string text = "   ";

期待される出力:
long expected = 0;

解説

Only spaces, so there are no words: 0.

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。