Leetcode#179 Largest Number

原题地址

 

先将数字转成字符串,然后排序,让能够组成更大数字的字符串放在前面,最后拼接成完整的字符串即可。

有种很巧妙的方法判断两个字符串的大小关系,假设两个字符串是A,B,则比较AB和BA,若AB比BA大,说明A应该放在前面,即A<B,其他同理。

 

代码:

 1 string largestNumber(vector<int> &num) {
 2         string res;
 3         
 4         vector<string> strs;
 5         for (auto n : num)
 6             strs.push_back(to_string(n));
 7 
 8         sort(strs.begin(), strs.end(), [](string &a, string &b) {return (a + b) > (b + a);});
 9 
10         for (auto str : strs) {
11             if (str == "0" && res.empty())
12                 continue;
13             res += str;
14         }
15     
16         return res.empty() ? "0" : res;
17 }

 

posted @ 2015-01-26 16:51  李舜阳  阅读(376)  评论(0编辑  收藏  举报