簡単 0件解決済み 正答率0%

Mad Lib Builder

Fill the bracketed blanks of a story template with words, in order.

このチャレンジで学べること

  • Find bracketed parts inside a string
  • Replace them in order with list items
  • Handle running out of replacement words

問題

翻訳を表示

In a word game, one player writes a story with blanks and the others call out words without seeing the story. A blank is written as a hint in square brackets, such as [noun] or [number]. Replace the first blank with the first word, the second blank with the second word, and so on, brackets and hint included. If there are fewer words than blanks, the blanks left over stay exactly as they are; extra words are not used.

Implement mad_lib_builder(template, words).

Input

template: The story. Every [ is closed by a later ], with no brackets nested inside a blank.

words: The words to put in the blanks, in order.

Output

Return the finished story.

制約

0 ≤ length of template ≤ 1000

0 ≤ length of words ≤ 100, each word has at most 30 characters and no square brackets

例

例 1
入力:
template = "My [animal] ate [number] [food] for breakfast."
words = ["hamster", "12", "pancakes"]

期待される出力:
expected = "My hamster ate 12 pancakes for breakfast."
入力:
std::string template = "My [animal] ate [number] [food] for breakfast.";
std::vector<std::string> words = {"hamster", "12", "pancakes"};

期待される出力:
std::string expected = "My hamster ate 12 pancakes for breakfast.";
入力:
string template = "My [animal] ate [number] [food] for breakfast.";
string[] words = new string[] {"hamster", "12", "pancakes"};

期待される出力:
string expected = "My hamster ate 12 pancakes for breakfast.";

解説

Each blank takes the next word: "My hamster ate 12 pancakes for breakfast.".

例 2
入力:
template = "The [adjective] [noun] sang."
words = ["sleepy"]

期待される出力:
expected = "The sleepy [noun] sang."
入力:
std::string template = "The [adjective] [noun] sang.";
std::vector<std::string> words = {"sleepy"};

期待される出力:
std::string expected = "The sleepy [noun] sang.";
入力:
string template = "The [adjective] [noun] sang.";
string[] words = new string[] {"sleepy"};

期待される出力:
string expected = "The sleepy [noun] sang.";

解説

Only one word was given, so the second blank stays: "The sleepy [noun] sang.".

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

Scan the template character by character and copy normal characters straight to the result.

ヒント 2

When you see `[`, find the matching `]` and treat everything in between as one blank.

ヒント 3

Keep a counter of blanks seen; if it reaches the number of words, copy the blank unchanged.

目安の計算量

O(n + total word length) time, O(n) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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