Ac solution code


  • 0

    The solution is based on sorting Comparator class. The key part is comparing s2+s1 and s1+s2, instead of characters inside s1 and s2.

    public String largestNumber(int[] nums) {
    	if (nums == null || nums.length == 0) return "0";
        String strs[] = new String[nums.length];
        for (int i = 0; i < nums.length; i++) 
        	strs[i] = String.valueOf(nums[i]);
        
        Arrays.sort(strs, new Comparator<String>() {// Sorting Comparator
        	public int compare(String s1, String s2) {// Compare s2+s1 and s1+s2, instead of characters inside s1 and s2.
        		return (s2+s1).compareTo(s1+s2); 
        	};
        });
        StringBuilder sb = new StringBuilder();
        for (String s : strs) 
            sb.append(s);      
        String res = sb.toString();
        int index = 0;
        while (index < res.length() && res.charAt(index) == '0')// Trim 0 at the beginning
        	index++; 	
        res = res.substring(index);
        return res.length() == 0 ? "0" : res;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.