Leetcode 228 Solution

This article provides solution to leetcode question 228 (summary-ranges)

https://leetcode.com/problems/summary-ranges

Solution

class Solution {
public:
    vector<string> summaryRanges(vector<int>& nums) {
        int last_start = 0;
        int last_val = 0;
        vector<string> res;

        if (nums.size() == 0)
            return res;

        for (int j = 0; j < nums.size(); j++)
        {
            if (j == 0)
                last_start = 0;
            else
            {
                if (nums[j] != nums[j - 1] + 1)
                {
                    if (last_start == j - 1)
                        res.push_back(to_string(nums[j - 1]));
                    else
                        res.push_back(to_string(nums[last_start]) + "->" + to_string(nums[j - 1]));

                    last_start = j;
                }
            }
        }

        if (last_start == nums.size() - 1)
            res.push_back(to_string(nums[nums.size() - 1]));
        else
            res.push_back(to_string(nums[last_start]) + "->" + to_string(nums[nums.size() - 1]));

        return res;
    }
};