โจทย์
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
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน