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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
先考虑字符串的长短
class Solution {
string itoa(int num) {
stringstream stream;
stream << num;
return stream.str();
}
static bool comp(const string& str1, const string& str2) {
if(str1.size() > str2.size() || str2.empty()) return !comp(str2, str1);
if(str1.empty()) {
return !str2.empty();
}
int i = 0;
while( i < str1.size() ) {
if(str1[i] > str2[i]) return true;
if(str1[i] < str2[i]) return false;
i++;
}
string str2_next = i== str2.size() ? "" : str2.substr(i);
return comp(str1, str2_next);
return false;
}
public:
string largestNumber(vector<int>& nums) {
vector<string> rst;
for( int num : nums ) {
rst.push_back(itoa(num));
}
sort(rst.begin(), rst.end(), comp);
string str;
for( string s : rst ) {
str.append(s);
}
int i = 0;
while( i < str.size() && str[i] == '0') i++;
return i == str.size() ? "0" : str.substr(i);
}
};