https://school.programmers.co.kr/learn/courses/30/lessons/131128
숫자로된 문자열을 꺼내서 조건에 맞는 수를 조합하여 가장 큰 수를 문자열로 리턴
각 인덱스가 해당 숫자이고 값이 해당 숫자의 개수이다.
class Solution {
public String solution(String X, String Y) {
String answer = "";
int[] Xarr = new int[10];
int[] Yarr = new int[10];
int[] result = new int[10];
int cnt = 0;
StringBuilder sb = new StringBuilder();
for(String s : X.split("")){
Xarr[Integer.parseInt(s)]++;
}
for(String s : Y.split("")){
Yarr[Integer.parseInt(s)]++;
}
for(int i = 0; i < result.length; i++) {
if(Xarr[i] > 0 && Yarr[i] > 0){
result[i] = Math.min(Xarr[i], Yarr[i]);
cnt++;
}
}
int sum = 0;
for(int i = 9; i >= 0; i--){
for(int j = 0; j < result[i]; j++){
if(result[i] > 0){
sb.append(String.valueOf(i));
sum += i;
}
}
}
if(cnt == 0) return "-1";
else if(cnt > 0 && sum == 0) return "0";
return sb.toString();
}
}
너무느리다... parseInt와 String.valueOf를 남발해서 그런가 값이 커지면 느리다..
class Solution {
public String solution(String X, String Y) {
StringBuilder answer = new StringBuilder();
int[] x = {0,0,0,0,0,0,0,0,0,0};
int[] y = {0,0,0,0,0,0,0,0,0,0};
for(int i=0; i<X.length();i++){
x[X.charAt(i)-48] += 1;
}
for(int i=0; i<Y.length();i++){
y[Y.charAt(i)-48] += 1;
}
for(int i=9; i >= 0; i--){
for(int j=0; j<Math.min(x[i],y[i]); j++){
answer.append(i);
}
}
if("".equals(answer.toString())){
return "-1";
}else if(answer.toString().charAt(0)==48){
return "0";
}else {
return answer.toString();
}
}
}