https://school.programmers.co.kr/learn/courses/30/lessons/131128
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음 시도해봤던 코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(string X, string Y) {
string answer = "";
int zeroCnt = 0;
sort(X.begin(), X.end(), greater<>());
sort(Y.begin(), Y.end(), greater<>());
for(int i = 0; i < X.size(); ++i)
for(int j = 0; j < Y.size(); ++j)
if(X[i] == Y[j]) {
Y.erase(Y.begin() + j);
if(X[i] == '0')
++zeroCnt;
else
answer += X[i];
break;
}
while(zeroCnt > 0){
answer += '0';
--zeroCnt;
}
if(answer == "") answer = "-1";
else if(answer[0] == '0') answer = "0";
return answer;
}
몇몇 테스트 케이스에서 시간초과가 났다.
다시 작성한 코드
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
string solution(string X, string Y) {
string answer = "";
int XCount[10] = {};
int YCount[10] = {};
for(int i = 0; i < X.size(); ++i)
++XCount[X[i] - 48];
for(int i = 0; i < Y.size(); ++i)
++YCount[Y[i] - 48];
for(int i = 9; i >= 0; --i){
while(XCount[i] > 0 && YCount[i] > 0){
answer += (i + 48);
--XCount[i];
--YCount[i];
}
}
if(answer == "") answer = "-1";
else if(answer[0] == '0') answer = "0";
return answer;
}
문자열에 있는 숫자를 하나하나 세어서 그 결과를 비교했다.
'알고리즘 공부' 카테고리의 다른 글
ios::sync_with_studio(false), cin.tie(NULL), endl와 “\n” (0) | 2024.05.09 |
---|---|
프로그래머스 햄버거 만들기 C++ (0) | 2024.04.23 |
프로그래머스 136798. 기사단원의 무기 (1) | 2023.12.27 |
백준 10815번 숫자 카드 C++ (0) | 2023.10.16 |
백준 2805번 나무자르기 C++ (1) | 2023.10.10 |