
아래는 프로그래머스에서 제공한 문제 설명입니다.
코니는 영어 단어가 적힌 카드 뭉치 두 개를 선물로 받았습니다. 코니는 다음과 같은 규칙으로 카드에 적힌 단어들을 사용해 원하는 순서의 단어 배열을 만들 수 있는지 알고 싶습니다.
예를 들어 첫 번째 카드 뭉치에 순서대로 ["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 함수를 완성해주세요.
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public string solution(string[] cards1, string[] cards2, string[] goal) {
string answer = "";
Stack<string> card1Stack = new Stack<string>(cards1.Reverse());
Stack<string> card2Stack = new Stack<string>(cards2.Reverse());
foreach(var word in goal)
{
if(card1Stack.Count != 0 && word == card1Stack.Peek())
card1Stack.Pop();
else if (card2Stack.Count != 0 && word == card2Stack.Peek())
card2Stack.Pop();
else return "No";
}
answer = "Yes";
return answer;
}
}
using System;
public class Solution {
public string solution(string[] cards1, string[] cards2, string[] goal) {
string answer = "";
int idx1 = 0;
int idx2 = 0;
foreach(var word in goal)
{
if(idx1 < cards1.Length && word == cards1[idx1])
idx1++;
else if(idx2 < cards2.Length && word == cards2[idx2])
idx2++;
else return "No";
}
answer = "Yes";
return answer;
}
}
처음에 하나씩 빼가면서 비교를 하는거라 Stack이 떠올라 스택으로 작성을 했는데,
int 두개만 생성해서 하는 방법이 있었다... 훨씬 빠르고 간편