-
Notifications
You must be signed in to change notification settings - Fork 16
/
RestoreIPAddresses.java
57 lines (51 loc) · 1.82 KB
/
RestoreIPAddresses.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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class RestoreIPAddresses {
public List<String> restoreIpAddresses(final String s) {
final List<String> result = new ArrayList<>();
restoreIpAddresses(s, result, new LinkedList<>(), 0);
return result;
}
private void restoreIpAddresses(final String s, final List<String> result, LinkedList<Integer> numbers, int index) {
if (numbers.size() == 4 && index == s.length()) {
result.add(ipAddressFrom(numbers));
return;
}
if (numbers.size() >= 4 || index == s.length()) {
return;
}
for (int i = index + 1 ; i <= s.length() ; i++) {
if (isValidIpAddressInteger(s, index, i)) {
numbers.add(toNumber(s, index, i));
restoreIpAddresses(s, result, numbers, i);
numbers.removeLast();
} else {
break;
}
}
}
private String ipAddressFrom(LinkedList<Integer> numbers) {
StringBuilder result = new StringBuilder();
for (int number : numbers) {
result.append(number).append('.');
}
result.deleteCharAt(result.length() - 1);
return result.toString();
}
private boolean isValidIpAddressInteger(String s, int start, int end) {
if (hasLeadingZeros(s, start, end)) return false;
return toNumber(s, start, end) < 256;
}
private boolean hasLeadingZeros(String s, int start, int end) {
return end - start > 1 && s.charAt(start) == '0';
}
private int toNumber(String s, int start, int end) {
int val = 0;
for (int index = start ; index < end ; index++) {
val *= 10;
val += s.charAt(index) - '0';
}
return val;
}
}