ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Longest Word

Find the longest word in a sentence.

สิ่งที่คุณจะได้เรียนรู้

  • Split a sentence into words
  • Track the longest word seen so far
  • Break ties by keeping the first one

โจทย์

ดูฉบับแปล

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
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.

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

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

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

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

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

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