問題
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
例
入力:
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.
入力:
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用に調整されています。上記の説明と制約に従ってください。