Posted on

Description

Submission

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        if(nums.empty()) return {};
        
        int n = nums.size();

        stringstream ss;
        ss << nums[0];

        if(nums.size() == 1) {
            return {ss.str()};
        }
        
        vector<string> rets;
        int beg = 0;
        for(int i = 1; i < nums.size(); ++i) {
            if((long long)nums[i] - nums[i-1] != 1) {
                if(beg != i - 1) {
                    ss << "->" << nums[i-1];
                } 
                rets.push_back(ss.str());
                ss.str("");
                ss << nums[i];
                beg = i;
            }
        }
        if(beg != n - 1) {
            ss << "->" << nums[n-1];
        }

        rets.push_back(ss.str());

        return rets;

    }
};

Leave a Reply

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