合并连续数字的算法

public class Test {
	public static void main(String[] args) {
		String str = new String(
				"1,2,3,4,5,6,7,8,9,11,13,14,1000,1001,1002,1003");
		String[] s = str.split(",");
		int[] num = new int[s.length];
		String result = "";
		for (int i = 0; i < s.length; i++) {
			num[i] = Integer.parseInt(s[i]);
		}
		for (int i = 0; i < num.length; i++) {
			if (i == 0) {
				result = "" + num[i];
			} else if (i == num.length - 1) {
				if (num[i] - num[i - 1] == 1) {
					result = result + "-" + num[i];
				} else {
					result = result + "," + num[i];
				}
			} else {
				if ((num[i] - num[i - 1] == 1) && (num[i + 1] - num[i] == 1)) {
					continue;
				}
				if ((num[i] - num[i - 1] == 1) && (num[i + 1] - num[i] != 1)) {
					result = result + "-" + num[i];
				}
				if ((num[i] - num[i - 1] != 1)) {
					result = result + "," + num[i];
				}

			}

		}
		System.out.println(result);
	}
}

你可能感兴趣的:(数据结构和算法)