Đề bài
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.
Ràng buộc
0 ≤ length of template ≤ 1000
0 ≤ length of words ≤ 100, each word has at most 30 characters and no square brackets
Ví dụ
Đầu vào:
template = "My [animal] ate [number] [food] for breakfast."
words = ["hamster", "12", "pancakes"]
Kết quả mong đợi:
expected = "My hamster ate 12 pancakes for breakfast."
Đầu vào:
std::string template = "My [animal] ate [number] [food] for breakfast.";
std::vector<std::string> words = {"hamster", "12", "pancakes"};
Kết quả mong đợi:
std::string expected = "My hamster ate 12 pancakes for breakfast.";
Đầu vào:
string template = "My [animal] ate [number] [food] for breakfast.";
string[] words = new string[] {"hamster", "12", "pancakes"};
Kết quả mong đợi:
string expected = "My hamster ate 12 pancakes for breakfast.";
Giải thích
Each blank takes the next word: "My hamster ate 12 pancakes for breakfast.".
Đầu vào:
template = "The [adjective] [noun] sang."
words = ["sleepy"]
Kết quả mong đợi:
expected = "The sleepy [noun] sang."
Đầu vào:
std::string template = "The [adjective] [noun] sang.";
std::vector<std::string> words = {"sleepy"};
Kết quả mong đợi:
std::string expected = "The sleepy [noun] sang.";
Đầu vào:
string template = "The [adjective] [noun] sang.";
string[] words = new string[] {"sleepy"};
Kết quả mong đợi:
string expected = "The sleepy [noun] sang.";
Giải thích
Only one word was given, so the second blank stays: "The sleepy [noun] sang.".
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Scan the template character by character and copy normal characters straight to the result.
Gợi ý 2
When you see `[`, find the matching `]` and treat everything in between as one blank.
Gợi ý 3
Keep a counter of blanks seen; if it reaches the number of words, copy the blank unchanged.
Độ phức tạp mong đợi
O(n + total word length) time, O(n) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.