[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.
老题了,主要是搞懂cmp函数,前置0的处理还有待优化,不用copy两遍字符串。
1 bool cmp(const string s1, const string s2) { 2 return (s1 + s2) > (s2 + s1); 3 } 4 5 class Solution { 6 public: 7 string largestNumber(vector<int> &num) { 8 vector<string> s_num(num.size()); 9 stringstream stream; 10 for (int i = 0; i < num.size(); ++i) { 11 stream << num[i]; 12 stream >> s_num[i]; 13 stream.clear(); 14 } 15 sort(s_num.begin(), s_num.end(), cmp); 16 string tmp_res; 17 for (int i = 0; i < s_num.size(); ++i) { 18 tmp_res += s_num[i]; 19 } 20 string res; 21 bool flag = false; 22 for (int i = 0; i < tmp_res.size(); ++i) { 23 if (tmp_res[i] != '0') { 24 res.push_back(tmp_res[i]); 25 flag = true; 26 } else if (flag) { 27 res.push_back(tmp_res[i]); 28 } 29 } 30 if (!flag) res.push_back('0'); 31 return res; 32 } 33 };
因为字符串是从int转过来的,所以不会出现0123这样的数字,所以前置0只有一种情况,那就是“0”,所以处理前置0时只要考虑“0”这一种特殊情况就行了。
1 class Solution { 2 public: 3 static bool cmp(const string &s1, const string &s2) { 4 return (s1 + s2) > (s2 + s1); 5 } 6 string largestNumber(vector<int> &num) { 7 vector<string> s_num(num.size()); 8 for (int i = 0; i < num.size(); ++i) { 9 s_num[i] = to_string(num[i]); 10 } 11 sort(s_num.begin(), s_num.end(), cmp); 12 string res; 13 bool flag = false; 14 for (int i = 0; i < s_num.size(); ++i) { 15 if (s_num[i] != "0") { 16 res += s_num[i]; 17 flag = true; 18 } else if (flag) { 19 res += s_num[i]; 20 } 21 } 22 if (!flag) res.push_back('0'); 23 return res; 24 } 25 };