若传入参数值21~40,51~100,41~42,1~50(该参数类型可为string,string[]或list)合并结果为1~100,21~42(类型可同传入参数)。传入参数可以重复,如:21~40,51~100,41~42,1~50,1~50,返回结果也同上。
4 回答
哔哔one
TA贡献1854条经验 获得超8个赞
//new String[]{"21~40","51~100","41~42","1~50"} public static Object merge(Object o) { if(o instanceof String[]) { String[] numbers = (String[])o; int resultLength = numbers.length; for(int i = 0; i < numbers.length; i++) { if(numbers[i] == null) continue; int start = getStart(numbers[i]); int end = getEnd(numbers[i]); if(start > end) continue; for(int j = 0; j < numbers.length; j++) { if(i == j || numbers[j] == null) continue; int nextStart = getStart(numbers[j]); int nextEnd = getEnd(numbers[j]); if(start == (nextEnd + 1)) { numbers[i] = nextStart + delimiter + end; numbers[j] = null; resultLength--; } } } String[] result = new String[resultLength]; int index = 0; for(int i = 0; i < numbers.length; i++) { if(numbers[i] == null) continue; result[index++] = numbers[i]; System.out.println(numbers[i]); } return result; } return null; }
只写了string[]类型的,list等参数类型按照这个思路自己补充就行了
千巷猫影
TA贡献1829条经验 获得超7个赞
忘记两个方法了
[code="java"]
private static final String delimiter = "~";
public static int getStart(String number)
{
String start = number.substring(0, number.indexOf(delimiter));
return Integer.valueOf(start);
}
public static int getEnd(String number) { String end = number.substring(number.indexOf(delimiter) + 1); return Integer.valueOf(end); }
添加回答
举报
0/150
提交
取消