問題
ある言葉遊びでは、1人が空欄のある物語を書き、ほかの人は物語を見ないまま単語を言っていきます。空欄は [noun] や [number] のように、角かっこで囲んだヒントとして書かれます。最初の空欄を1つ目の単語で、2番目の空欄を2つ目の単語で、というように順に置き換えてください。置き換えるのは、角かっことヒントを含めた空欄全体です。単語が空欄より少ない場合、残った空欄はそのまま残し、余った単語は使いません。
mad_lib_builder(template, words) を実装してください。
入力
template: 物語。すべての [ は後ろにある ] で閉じられ、空欄の中で角かっこが入れ子になることはありません。
words: 空欄に入れる単語(順番どおり)。
出力
完成した物語を返してください。
制約
0 ≤ template の長さ ≤ 1000
0 ≤ words の長さ ≤ 100、各単語は30文字以下で角かっこを含まない
例
入力:
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.";
解説
各空欄に次の単語が入ります。結果は "My hamster ate 12 pancakes for breakfast." です。
入力:
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.";
解説
単語が1つしかないので、2番目の空欄は残ります。結果は "The sleepy [noun] sang." です。
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
テンプレートを1文字ずつ走査し、普通の文字はそのまま結果にコピーしましょう。
ヒント 2
`[` を見つけたら対応する `]` を探し、その間をまとめて1つの空欄として扱います。
ヒント 3
見つけた空欄の数を数えておき、単語の数に達したら空欄をそのままコピーします。
目安の計算量
時間 O(n + total word length)、追加メモリ O(n)(total word length は単語の長さの合計)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。