코니는 영어 단어가 적힌 카드 뭉치 두 개를 선물로 받았습니다. 코니는 다음과 같은 규칙으로 카드에 적힌 단어들을 사용해 원하는 순서의 단어 배열을 만들 수 있는지 알고 싶습니다.
예를 들어 첫 번째 카드 뭉치에 순서대로 ["i", "drink", "water"], 두 번째 카드 뭉치에 순서대로 ["want", "to"]가 적혀있을 때 ["i", "want", "to", "drink", "water"] 순서의 단어 배열을 만들려고 한다면 첫 번째 카드 뭉치에서 "i"를 사용한 후 두 번째 카드 뭉치에서 "want"와 "to"를 사용하고 첫 번째 카드뭉치에 "drink"와 "water"를 차례대로 사용하면 원하는 순서의 단어 배열을 만들 수 있습니다.
문자열로 이루어진 배열 cards1, cards2와 원하는 단어 배열 goal이 매개변수로 주어질 때, cards1과 cards2에 적힌 단어들로 goal를 만들 있다면 "Yes"를, 만들 수 없다면 "No"를 return하는 solution 함수를 완성해주세요.

#include <string>
#include <vector>
#include <iostream>
using namespace std;
string solution(vector<string> cards1, vector<string> cards2, vector<string> goal) {
string answer = "";
int ptr1 = 0;
int ptr2 = 0;
for(int i=0; i<goal.size(); i++) {
if(cards1[ptr1] == goal[i]) {
if(ptr1 < cards1.size()-1) {
ptr1 += 1;
}
else continue;
}
else if(cards2[ptr2] == goal[i]) {
if(ptr2 < cards2.size()-1) {
ptr2 += 1;
}
else continue;
}
else return "No";
}
return "Yes";
}
단순구현 문제로 카드뭉치 두개를 각각 순회하는 포인터를 정의하여 시간복잡도 n으로 풀었다.
문제를 보아하는 queue 자료형이 잘어울리는 문제 같아서 연습겸 queue로도 풀어봤다.
#include <string>
#include <vector>
#include <iostream>
#include <deque>
using namespace std;
string solution(vector<string> cards1, vector<string> cards2, vector<string> goal) {
string answer = "";
deque<string> deq1(cards1.begin(), cards1.end());
deque<string> deq2(cards2.begin(), cards2.end());
deque<string> deq_goal(goal.begin(), goal.end());
for(int i=0; i<goal.size(); i++) {
if(!deq1.empty()) {
if(deq_goal.front() == deq1.front()) {
deq1.pop_front();
deq_goal.pop_front();
}
}
if(!deq2.empty()) {
if(deq_goal.front() == deq2.front()) {
deq2.pop_front();
deq_goal.pop_front();
}
}
}
if(!deq_goal.empty()) return "No";
return "Yes";
}
시간복잡도는 똑같이 n이라 런타임은 비슷했다.