Compress Number List – AlgoBox by dietpepsi
Given a sorted array return it in compressed format by replacing consecutive segments with the short form.
Example
Given a sorted array return it in compressed format by replacing consecutive segments with the short form.
Example
nums
= [1,2,3,10,25,26,30,31,32,33]
compressed
= "1-3,10,25-26,30-33"
public String compress(int... nums) {
if (nums.length == 0) return "";
StringBuilder builder = new StringBuilder();
int start = nums[0], end = nums[0];
for (int x: nums) {
if (x == end) continue;
if (x == end + 1) end++;
else {
builder.append(start);
if (end > start) builder.append("-").append(end);
builder.append(",");
start = end = x;
}
}
builder.append(start);
if (end > start) builder.append("-").append(end);
return builder.toString();
}
Read full article from Compress Number List – AlgoBox by dietpepsi