Problem Statement:
I have an array of non-negative numbers in form of String in Java, I want to arrange the integers to form the largest possible number.
Example: Given below input:
String[] numbers = {"15", "9", "62", "34"};
The arrangement "9623415" gives the largest number.
Note: I understand we can sort all numbers in descending order, but simply sorting doesn’t work. For example, 15 is larger than 9 in natural order but "9" comes before "15" in the solution. What's the best way to implement a custom comparator in this case?
Any help would be appreciated.
解决方案
the method public int compareTo(String anotherString) of a String is what you need which gives you the order of the String lexicographically .
Update1:
What is lexicographic ordering.
Frome Java Doc:
This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string -- that is, the value:
this.charAt(k)-anotherString.charAt(k)
If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings -- that is, the value:
this.length()-anotherString.length()
So String 9will appear ahead of String 15 in a lexicographic ordering, since they have different characters at index 0, and char 9 is larger than char 1. If you read about lexicographic ordering carefully you will find that that order is just what the OP needs!
Update2: Why lexicographic ordering is the key for this question
The lexicographic order of the Strings in the question is like this:
"9", "62", "34","15"
So after you get this order, the question should be trival: just iterate the ordered sequence and you get the answer.
Update 3: How to handle special case like: "9"&"90", since we need "990" instead of "909"
In this case the lexicographic ordering will fail. But it is easy to figure out a fix:
Instead of str1.compareTo(str2), we can use (str2+str1).compareTo(str1+str2). The key here is to ensure these two strings have at least a bit of different digit, so we don't get the order by comparing there lengths.