ง่าย 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

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

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก