समस्या
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 के लिए अनुकूलित की गई है। ऊपर दिए गए स्टेटमेंट और सीमाओं का पालन करें।