首页 > 代码库 > [LeetCode] Largest Number

[LeetCode] Largest Number

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.

这道题目一开始花了不少时间,思路也不好。把数字转换成字符串,方便不同长度的字符串从左往右逐个字符比较。但如果某一个字符串是另一个的前缀的话,即使把多余字符串和第一个字符比较,也还是遇到了不少情况要处理。

这题最简单的方法其实是,比较两个字符串s1和s2时,比较s1+s2和s2+s1即可。注意这里有一个特殊情况,就是组合后的字符串以0开始,需要把开始的0都去掉。


    class StringComparator implements Comparator<String> {
		@Override
		public int compare(String s1, String s2) {
			String s12 = s1 + s2;
			String s21 = s2 + s1;

			return (int) (Long.parseLong(s12) - Long.parseLong(s21));
		}
	}    
    
    public String largestNumber(int[] num) {
		StringBuilder sb = new StringBuilder();

		List<String> numStr = new ArrayList<String>();
		for (int i : num) {
			numStr.add("" + i);
		}
		Collections.sort(numStr, new StringComparator());

        <span style="white-space:pre">	</span>// Trim the leading zero(s).
		boolean HasPossibleLeading0 = true;
		for (int i = numStr.size() - 1; i >= 0; --i) {
			if (HasPossibleLeading0 && numStr.get(i).equals("0"))
				continue;
			HasPossibleLeading0 = false;
			sb.append(numStr.get(i));
		}
		if (sb.length() == 0) {
			return "0";
		}

		return sb.toString();
    }






[LeetCode] Largest Number