-
Notifications
You must be signed in to change notification settings - Fork 2
/
StringRun.java
58 lines (53 loc) · 1.51 KB
/
StringRun.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.*;
public class StringRun {
public static String rangeExtraction(int[] arr) {
List<String> solution = new ArrayList<String>();
int lowIndex = 0;
Boolean onARun = false;
for (int i = 0; i < arr.length; i++) {
if (onARun) {
if (arr.length - 1 == i) {
// we're on a run and at the end
if (i - lowIndex >= 2) {
String run = arr[lowIndex] + "-" + arr[i];
solution.add(run);
} else {
for (int start = lowIndex; start <= i; start++) {
solution.add("" + arr[start]);
}
}
} else if (arr[i+1] - arr[i] == 1) {
// we're on a run so lets keep it going
continue;
} else {
onARun = false;
if (i - lowIndex >= 2) {
String run = arr[lowIndex] + "-" + arr[i];
solution.add(run);
} else {
for (int start = lowIndex; start <= i; start++) {
solution.add("" + arr[start]);
}
}
}
} else {
if (arr.length - 1 == i) {
solution.add("" + arr[i]);
} else if (arr[i+1] - arr[i] == 1) {
lowIndex = i;
onARun = true;
} else {
solution.add("" + arr[i]);
}
}
}
String stringResult = "";
for (int i = 0; i < solution.size(); i++) {
stringResult += solution.get(i);
if (i != solution.size() -1) {
stringResult += ",";
}
}
return stringResult;
}
}