您的位置:首页 > 其它

LeetCode OJ 之 Summary Ranges

2015-07-10 11:20 232 查看
题目:

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given 
[0,1,2,4,5,7]
, return 
["0->2","4->5","7"].

把连续的转化成0->2这种形式存储在string里。
思路:

代码:

class Solution {
public:
vector<string> summaryRanges(vector<int>& nums)
{
vector<string> result;
string path;
int len = nums.size();
if(len == 0)
return result;
int i = 0 ;
for(; i < len-1 ; i++)
{
if(nums[i] != nums[i+1] - 1)
{
//如果path之前非空,则加上->,如果为空,则只有一个字符
if(path != "")
path += "->";
path += to_string(nums[i]);
result.push_back(path);
path.clear();
}
else
//如果path之前为空,则把当前数字作为开头
if(path == "")
path = to_string(nums[i]);
}
//加上最后一个数字
if(path != "")
path += "->";
path += to_string(nums[i]);
result.push_back(path);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: