题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Solution {
public String PrintMinNumber(int[] numbers) {
if(numbers == null || numbers.length == 0) {
return new String();
}
List<String> array = new ArrayList<String>();
for(int i = 0; i < numbers.length; i++) {
String str = String.valueOf(numbers[i]);
array.add(str);
}
Collections.sort(array, new Comparator<String>(){
public int compare(String str1, String str2) {
int len1 = str1.length();
int len2 = str2.length();
int i = 0;
int j = 0;
while(i < len1 && j < len2) {
if(str1.charAt(i) > str2.charAt(j))
return 1;
else if(str1.charAt(i) < str2.charAt(j))
return -1;
else {
i ++;
j ++;
if(i == len1 && j < len2)
i = 0;
if( i < len1 && j == len2)
j = 0;
}
}
return 0;
}
});
String s = new String();
for(String str : array) {
s += str;
}
return s;
}
public static void main(String [] args) {
Solution obj = new Solution();
int [] array = { 3, 321, 32};
obj.PrintMinNumber(array);
}
}