*LeetCode-Largest Number

string有一个函数是compareTo 比较两个string大小 先比长度 然后每一位比 直到一个比一个大 

所以写了一个comparator 但是注意要用两个string先前后加起来 使长度一样 才有可比性

public class Solution {
    public String largestNumber(int[] nums) {
        if ( nums == null || nums.length == 0 )
            return "";
        Comparator<String> comp = new Comparator<String> (){
            public int compare ( String s1, String s2 ){
                String res1 = s1 + s2;
                String res2 = s2 + s1;
                return res2.compareTo( res1 );
            }
        };
        String [] strs = new String [ nums.length ];
        for ( int i = 0; i < nums.length; i ++ ){
            strs[ i ] = Integer.toString ( nums[ i ] );
        }
        Arrays.sort ( strs, comp );
        if ( strs[ 0 ].equals ("0") )
            return "0";
        StringBuilder sb = new StringBuilder();
        for ( String st : strs ){
            sb.append ( st );
        }
        return sb.toString();
    }
}


你可能感兴趣的:(*LeetCode-Largest Number)