문제 풀기/C#
63. 숫자 짝수 (Dictionary)
kagan-draca
2025. 2. 11. 17:34
풀이 1) Dictionary
X, Y에 대한 Dicitionary로 key는 char, value는 int 형으로 만들어주고
X, Y를 순회하면서 각각의 요소의 수를 구해줬다.
그 후, Dictionary에서 Key 또는 Value를 이용해
Intersect(교집합), Union(합집합), Except(차집합)이 가능하다는 사실을 알게 되고
각 요소들의 교집합을 구한 후 내림차순 정렬했다.
교집합의 요소들을 순회하면서
Math.Min(dictX[commonKey], dictY[commonKey]);
으로 출력할 요소의 개수를 구하고
string.Concat()과 Enumerable.Repeat()로 요소를 문자열에 담아줬다.
마지막으로 문자열의 길이가 0이면 "-1"으로,
Substring(0, 1)이면 "0"으로 교체해 반환해줬다.
(가장 큰 수가 0은 뒤의 모든 수가 0을 의미)
using System;
using System.Linq;
using System.Collections.Generic;
public class Solution {
public string solution(string X, string Y)
{
Dictionary<char, int> dictX = new Dictionary<char, int>();
Dictionary<char, int> dictY = new Dictionary<char, int>();
for(int i = 0; i < X.Length; i++)
{
if(dictX.ContainsKey(X[i])) dictX[X[i]]++;
else dictX[X[i]] = 1;
}
for(int i = 0; i < Y.Length; i++)
{
if(dictY.ContainsKey(Y[i])) dictY[Y[i]]++;
else dictY[Y[i]] = 1;
}
List<char> commonKeys = dictX.Keys.Intersect(dictY.Keys).OrderByDescending(element => element).ToList();
string result = "";
foreach(char commonKey in commonKeys)
{
int min = Math.Min(dictX[commonKey], dictY[commonKey]);
result += string.Concat(Enumerable.Repeat(commonKey, min));
}
if(result.Length == 0) result = "-1";
if(result.Substring(0, 1) == "0") result = "0";
return result;
}
}
풀이 2)
풀이 1)을 바탕으로 X와 Y의 요소들의 개수를 배열을 이용해서 풀 수 있다는 사실을 발견했다.
(방식은 풀이 1)과 유사)
using System;
using System.Linq;
using System.Collections.Generic;
public class Solution {
public string solution(string X, string Y)
{
int[] tempX = new int[10];
int[] tempY = new int[10];
for(int i = 0; i < X.Length; i++) tempX[int.Parse(X[i].ToString())]++;
for(int i = 0; i < Y.Length; i++) tempY[int.Parse(Y[i].ToString())]++;
string result = "";
for(int i = 9; i >= 0; i--)
{
if(tempX[i] == 0 || tempY[i] == 0) continue;
int count = Math.Min(tempX[i], tempY[i]);
result += string.Concat(Enumerable.Repeat(i, count));
}
if(result.Length == 0) result = "-1";
if(result.Substring(0,1) == "0") result = "0";
return result;
}
}
풀이 1)과 풀이 2)의 수행시간을 비교했을 때
풀이 2)가 평균적인 수행시간이 풀이 1) 보다 짧지만
X, Y 문자열의 길이가 매우 길 경우는
풀이 1)의 수행시간이 더 짧은 것을 볼 수 있다.