Functions of StringBuilder:
代码:
public class Solution { public List<String> summaryRanges(int[] nums) { List<String> list = new ArrayList<>(); if(nums.length == 0) return list; int head = 0; int k = -1; StringBuilder sb = new StringBuilder(); for(int i = 0; i < nums.length; i++){ if(i == 0){ sb.append(nums[i]); if(i == nums.length-1){ list.add(sb.toString()); break; } sb.append(','); head = nums[i]; } else if(nums[i] > head + 1){ String[] tokens = sb.toString().split(","); if(tokens.length == 1) list.add(tokens[0]); if(tokens.length > 1){ String s = tokens[0]+"->"+tokens[tokens.length-1]; list.add(s); } sb = new StringBuilder(); sb.append(nums[i]); if(i == nums.length-1){ list.add(sb.toString()); break; } sb.append(','); head = nums[i]; } else{ sb.append(nums[i]); if(i == nums.length-1){ String[] tokens = sb.toString().split(","); String s = tokens[0]+"->"+tokens[tokens.length-1]; list.add(s); break; } sb.append(','); head = nums[i]; } } return list; } }
网上的代码:
public class Solution { public List<String> summaryRanges(int[] nums) { List<String> list = new ArrayList<>(); if(nums.length == 0) return list; int high = 0, low = 0; int length = nums.length; //int k = -1; while(high < length){ if(high < length-1 && nums[high]+1 == nums[high+1]){ high++; } else{ if(low == high) list.add(String.valueOf(nums[high])); else list.add(nums[low]+"->"+nums[high]); high++; low = high; } } return list; } }