剑指offer 把数组排列成最小的数字

class Solution {
public:
    static bool larger(const string& a, const string& b){
        if(a.empty()) return false;
        if(b.empty()) return true;
        int i = 0;
        while( i < a.size() && i < b.size()){
            if(a[i] > b[i]) return false;
            else if(a[i] < b[i]) return true;
            i++;
        }
        string a_b = a + b;
        string b_a = b + a;
        return a_b < b_a;
    }

    string PrintMinNumber(vector<int> numbers) {
        if(numbers.empty() ) return "";
        stringstream ss;
        if(numbers.size() == 1) {
            ss << numbers[0];
            return ss.str();
        }

        vector<string> nums(numbers.size());
        for(int i = 0; i < numbers.size(); i++){
            ss.str("");
            ss << numbers[i];
            nums[i] = ss.str();
        }

        sort(nums.begin(), nums.end(), larger);
        string res;
        for(string& s:nums){
            res += s;
        }
        return res;
    }
};
posted @ 2018-09-07 22:12  一条图图犬  阅读(139)  评论(0编辑  收藏  举报