Đề bài
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.
Ràng buộc
0 ≤ length ≤ 10,000
Ví dụ
Đầu vào:
text = "Learn to code today"
Kết quả mong đợi:
expected = 4
Đầu vào:
std::string text = "Learn to code today";
Kết quả mong đợi:
long long expected = 4;
Đầu vào:
string text = "Learn to code today";
Kết quả mong đợi:
long expected = 4;
Giải thích
Four words separated by spaces: 4.
Đầu vào:
text = " "
Kết quả mong đợi:
expected = 0
Đầu vào:
std::string text = " ";
Kết quả mong đợi:
long long expected = 0;
Đầu vào:
string text = " ";
Kết quả mong đợi:
long expected = 0;
Giải thích
Only spaces, so there are no words: 0.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
A word is any consecutive stretch of non-space characters.
Gợi ý 2
Scan through the text and count transitions from spaces into letters.
Gợi ý 3
Be careful with leading, trailing, and repeated spaces so you do not count empty runs.
Độ phức tạp mong đợi
O(n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.