https://school.programmers.co.kr/learn/courses/30/lessons/131128
unordered_map을 사용해서 Y를 분해하고 X원소를 for문을 돌려서 map에있는 해당 원소의 갯수를 토대로 answer를 완성한 뒤 sort하였다.
#include <vector>
#include <algorithm>
#include <unordered_map>
bool cmp(int a, int b)
{
return a > b;
}
using namespace std;
string solution(string X, string Y) {
string answer = "";
unordered_map<char,int> Ymap;
for(const auto& s : Y)
Ymap[s]++;
for(const auto& s : X)
if(Ymap[s]-- >= 1)
answer += s;
if(answer.length() == 0)
return "-1";
sort(answer.begin(), answer.end(),cmp);
if(answer[0] == '0')
return "0";
return answer;
}
#include <string>
#include <vector>
#include <map>
using namespace std;
string solution(string X, string Y)
{
string answer="";
map<char,int> mx;
for(char c : X) mx[c]++;
map<char,int> my;
for(char c : Y) my[c]++;
for(int i=9; i>=0; i--)
{
int num=min(mx[i+'0'],my[i+'0']);
for(int j=0; j<num; j++) answer+=i+'0';
}
if(answer=="") answer="-1";
else if(answer[0]=='0' && answer.size()>1) answer="0";
return answer;
}
map에 X와 Y를 분해해넣는다.
for문을 9부터 0까지 돌리는데 내림차순으로 바로 제일 큰 수 부터 넣어주기 위함이다.
mx와 my중 i값의 value가 작은 갯수만큼 answer에 i를 넣어준다.
그 후 나머지 예외 처리를 해준다.