179. Largest Number

来源:互联网 发布:怎样在淘宝上卖游戏币 编辑:程序博客网 时间:2024/05/16 08:18

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.

class NumbersComparator implements Comparator<String> {    @Override    public int compare(String s1, String s2) {        return (s2 + s1).compareTo(s1 + s2);    }}public class Solution {        public String largestNumber(int[] nums) {        String[] strs = new String[nums.length];        for (int i = 0; i < nums.length; i++) {            strs[i] = Integer.toString(nums[i]);        }        Arrays.sort(strs, new NumbersComparator());        StringBuilder sb = new StringBuilder();        for (int i = 0; i < strs.length; i++) {            sb.append(strs[i]);        }        String result = sb.toString();        int index = 0;        while (index < result.length() && result.charAt(index) == '0') {            index++;        }        if (index == result.length()) {            return "0";        }        return result.substring(index);    }}