Đề bài
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.
Ràng buộc
0 ≤ length ≤ 10,000
Ví dụ
Đầu vào:
text = "I love programming"
Kết quả mong đợi:
expected = "programming"
Đầu vào:
std::string text = "I love programming";
Kết quả mong đợi:
std::string expected = "programming";
Đầu vào:
string text = "I love programming";
Kết quả mong đợi:
string expected = "programming";
Giải thích
"programming" has 11 letters, more than the others.
Đầu vào:
text = "cat dog cow"
Kết quả mong đợi:
expected = "cat"
Đầu vào:
std::string text = "cat dog cow";
Kết quả mong đợi:
std::string expected = "cat";
Đầu vào:
string text = "cat dog cow";
Kết quả mong đợi:
string expected = "cat";
Giải thích
All are 3 letters; the first, "cat", wins.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Compare words by length while scanning the text once.
Gợi ý 2
Keep the first word seen with the maximum length so ties stay in order.
Gợi ý 3
Handle the case where the text has no words at all.
Độ 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.