码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 179: Largest Number

时间:2015-01-16 06:33:37      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

Largest Number

Total Accepted: 2269 Total Submissions: 15366

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 is9534330.

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

[分析]

按题目的要求, 重写排序方法, 然后排序即可.

[注意]

当一个数是另一个数的前缀时, 要注意顺序. 这里用了个小技巧   比较   S1+S2 ? S2+S1 即可.

另外, leading zeros要去掉.

[CODE]

public class Solution {
    public String largestNumber(int[] arr) {
        String[] strs = new String[arr.length];
		
		for(int i=0; i<arr.length; i++) {
			strs[i] = Integer.toString(arr[i]);
		}
		
		Arrays.sort(strs, new Comparator<String>() {
			@Override
			public int compare(String s1, String s2) {
				String ss1 = s1 + s2;
				String ss2 = s2 + s1;
				int i=0;
				while(i<ss1.length()) {
					if(ss1.charAt(i)!=ss2.charAt(i)) {
						return ss1.charAt(i) - ss2.charAt(i);
					}
					++i;
				}
				return 0;
			}
		}
				);
		
		StringBuilder sb = new StringBuilder();
		for(int i=strs.length-1; i>=0; i--) {
		    sb.append(strs[i]);
		}
		
		return sb.toString().replaceFirst("^0+(?!$)", "");	
    }
}


leetcode 179: Largest Number

标签:

原文地址:http://blog.csdn.net/xudli/article/details/42769549

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!