Problem
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.
Constraints
0 ≤ length ≤ 10,000
Examples
Input:
text = "I love programming"
Expected output:
expected = "programming"
Input:
std::string text = "I love programming";
Expected output:
std::string expected = "programming";
Input:
string text = "I love programming";
Expected output:
string expected = "programming";
Explanation
"programming" has 11 letters, more than the others.
Input:
text = "cat dog cow"
Expected output:
expected = "cat"
Input:
std::string text = "cat dog cow";
Expected output:
std::string expected = "cat";
Input:
string text = "cat dog cow";
Expected output:
string expected = "cat";
Explanation
All are 3 letters; the first, "cat", wins.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
Compare words by length while scanning the text once.
Hint 2
Keep the first word seen with the maximum length so ties stay in order.
Hint 3
Handle the case where the text has no words at all.
Expected complexity
O(n) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.