Your input
[0,1,2,4,5,7]
Your answer
["0->1->2","4->5"]
Expected answer
["0->2","4->5","7"]
Input:[0,2,3,4,6,8,9]
Output:["0->0","2->4","6->6","8"]
Expected:["0","2->4","6","8->9"]
50.15 %
// LC228 Beats 50.15 %
// There are 2 edge cases:
// 1.start == end like "6->6" should be treated as a single number "6", so we should check prev != start
// 2. Since discontinuous gap triggers adding String to result, the last String won't be added. We should deal with it before return
class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> result = new ArrayList<>();
if (nums == null || nums.length <= 0) return result;
int prev = nums[0];
int start = prev;
StringBuilder sb = new StringBuilder();
sb.append(start);
for (int i = 1; i < nums.length; i++) {
if (nums[i] != prev + 1) {
if (start != prev) sb.append("->" + prev);
result.add(sb.toString()); // add previous String to result
sb.setLength(0); // clear StringBuilder
start = nums[i];
sb.append(start); // new Starting point
}
prev = nums[i];
}
if (sb.length() != 0) {
if (start != prev) sb.append("->" + prev);
result.add(sb.toString());
}
return result;
}
}