โจทย์
Return the longest word in text (words are separated by spaces). If several words share the longest length, return the first one.
Implement longest_word(text).
Input
text: The sentence.
Output
Return the longest word, or an empty string if there are no words.
เงื่อนไข
0 ≤ length ≤ 10,000
ตัวอย่าง
อินพุต:
text = "I love programming"
ผลลัพธ์ที่คาดหวัง:
expected = "programming"
อินพุต:
std::string text = "I love programming";
ผลลัพธ์ที่คาดหวัง:
std::string expected = "programming";
อินพุต:
string text = "I love programming";
ผลลัพธ์ที่คาดหวัง:
string expected = "programming";
คำอธิบาย
"programming" has 11 letters, more than the others.
อินพุต:
text = "cat dog cow"
ผลลัพธ์ที่คาดหวัง:
expected = "cat"
อินพุต:
std::string text = "cat dog cow";
ผลลัพธ์ที่คาดหวัง:
std::string expected = "cat";
อินพุต:
string text = "cat dog cow";
ผลลัพธ์ที่คาดหวัง:
string expected = "cat";
คำอธิบาย
All are 3 letters; the first, "cat", wins.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Compare words by length while scanning the text once.
คำใบ้ 2
Keep the first word seen with the maximum length so ties stay in order.
คำใบ้ 3
Handle the case where the text has no words at all.
ความซับซ้อนที่คาดหวัง
O(n) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน