Posted on

Description

Submission

class Solution {
    string add(string str1, string str2) {
        if(str1 == "0") return str2;
        return str1 + str2;
    }
public:
    string largestNumber(vector<int>& nums) {
        vector<string> numsStr;
        for(int i = 0; i < nums.size(); ++i) {
            numsStr.push_back(to_string(nums[i]));
        }

        sort(numsStr.begin(), numsStr.end(), 
            [](string s1, string s2) {
                if(s1 == s2 || s1 == "0" || s2 == "0") return s1 > s2;
                string res1 = s1 + s2; 
                string res2 = s2 + s1; 
                for(int i = 0; i < res1.size(); ++i) {
                    if(res1[i] < res2[i]) return false;
                    if(res1[i] > res2[i]) return true;
                }
                return true;
            });

        string res = "";
        for(string s: numsStr) {
            res = add(res, s);
        }

        return res;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *