- Largest Number
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> numstr;
for (int n : nums) {
numstr.push_back(to_string(n));
}
sort(numstr.begin(), numstr.end(), [this](string lhs, string rhs) { return cmpf(lhs, rhs); });
string res = accumulate(numstr.begin(), numstr.end(), string(""));
return res.find_first_not_of('0') == string::npos ? "0" : res;
}
private:
bool cmpf(string lhs, string rhs) {
if (lhs.length() == rhs.length()) {
return lhs > rhs;
}
int m = lhs.length(), n = rhs.length();
int cmp = memcmp(lhs.data(), rhs.data(), min(m, n));
if (cmp != 0) {
return cmp > 0;
}
return m < n ? cmpf(lhs, rhs.substr(m)) : cmpf(lhs.substr(n), rhs);
}
};
网友评论