簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。