반응형
문자열 비교함수를 어떻게 커스텀하면 좋을지에 대한 의문이 있었는데
다른 분의 풀이를 보니, 발상의 전환을 하게 되었다.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(string& a, string& b) {
return b + a < a + b;
}
string solution(vector<int> numbers) {
string answer = "";
vector<string> strVector;
for(auto n : numbers) {
strVector.push_back(to_string(n));
}
sort(strVector.begin(), strVector.end(), cmp);
for(auto str : strVector) {
answer += str;
}
// 예외
if(answer[0] == '0')
return "0";
return answer;
}
참고로 테스트케이스 11번만 자꾸 틀려서 뭔가 했는데
입력이 [0, 0, 0, 0] 일 경우 "0000"이 아니라 "0"만 리턴해야 하는 예외가 있다.
그래서 if문으로 추가로 정의해줘야한다..
반응형
'[알고리즘 + 자료구조] > [프로그래머스]' 카테고리의 다른 글
프로그래머스 위장 C++ (0) | 2023.08.17 |
---|---|
프로그래머스 더 맵게 C++ (0) | 2023.08.15 |
프로그래머스 소수 찾기 C++ (0) | 2023.08.14 |
프로그래머스 큰 수 만들기 C++ (0) | 2023.08.14 |
프로그래머스 스킬 트리 C++ (0) | 2023.08.14 |