用java写一段方法 :1,2,4,生成字符串:L1~L2,L4; 1,4,5,6 生成字符串.L1,L4~L6;1,3,5,6 生成字符串.L1,L3,L5~L6
时间: 2023-08-21 21:05:04 浏览: 117
好的,根据您的要求,我写了以下Java方法来生成字符串:
```java
public static String generateString(int[] arr) {
StringBuilder sb = new StringBuilder();
int start = arr[0];
int end = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] - arr[i - 1] == 1) {
end = arr[i];
} else {
if (start == end) {
sb.append("L" + start + ",");
} else {
sb.append("L" + start + "~" + "L" + end + ",");
}
start = arr[i];
end = arr[i];
}
}
if (start == end) {
sb.append("L" + start);
} else {
sb.append("L" + start + "~" + "L" + end);
}
return sb.toString();
}
```
您可以将数组作为参数传递给该方法,例如:
```java
int[] arr = {1, 2, 4};
String result = generateString(arr);
System.out.println(result); // 输出 "L1~L2,L4"
```
```java
int[] arr = {1, 4, 5, 6};
String result = generateString(arr);
System.out.println(result); // 输出 "L1,L4~L6"
```
```java
int[] arr = {1, 3, 5, 6};
String result = generateString(arr);
System.out.println(result); // 输出 "L1,L3,L5~L6"
```
希望能够帮到您!
阅读全文