문제
한 단어 게임에서는 한 사람이 빈칸이 있는 이야기를 쓰고, 나머지 사람들은 이야기를 보지 않은 채 단어를 외칩니다. 빈칸은 [noun]이나 [number]처럼 대괄호 안에 힌트를 적어 표시합니다. 첫 번째 빈칸은 첫 번째 단어로, 두 번째 빈칸은 두 번째 단어로 바꾸는 식이며, 대괄호와 힌트까지 통째로 바꿉니다. 단어가 빈칸보다 적으면 남은 빈칸은 그대로 두고, 단어가 남으면 쓰지 않습니다.
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.";
설명
단어가 하나만 주어졌으므로 두 번째 빈칸은 그대로 남아 "The sleepy [noun] sang."이 됩니다.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
틀을 한 글자씩 훑으며 일반 문자는 결과에 그대로 복사하세요.
힌트 2
`[`가 보이면 짝이 되는 `]`를 찾아 그 사이 전체를 빈칸 하나로 처리하세요.
힌트 3
지금까지 본 빈칸 수를 세다가, 단어 수에 도달하면 빈칸을 그대로 복사하세요.
예상 복잡도
시간 O(n + total word length), 추가 공간 O(n)
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.