-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRestoreIPAdresses.java
More file actions
78 lines (55 loc) · 1.47 KB
/
Copy pathRestoreIPAdresses.java
File metadata and controls
78 lines (55 loc) · 1.47 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* URL: https://leetcode.com/problems/restore-ip-addresses/
*/
class Solution {
public static boolean isValid(String s) {
if (s.length() > 1) {
if(s.charAt(0) == '0') {
return false;
}
}
int sum = 0, factor = 1;
for (char c : s.toCharArray()) {
int sub = (int) c - 48;
sum = sum * factor + sub;
factor = 10;
}
if (sum > 255) {
return false;
}
return true;
}
public static boolean checkValidIP(String s, int left, int right, int limit, String interim, List<String> output) {
if (limit > 3) {
return false;
}
if (right > s.length()) {
return false;
}
if (!isValid(s.substring(left, right))) {
return false;
}
if (interim.isEmpty()){
interim = s.substring(left, right);
} else
interim = interim + "." + s.substring(left, right);
if (limit == 3 && right == s.length()) {
output.add(interim);
return true;
}
int start = right;
for (int i = 1; i <= 3 ; i++) {
checkValidIP(s, start, start + i, limit + 1, interim, output));
}
return false;
}
public static List<String> restoreIpAddresses(String s) {
List<String> output = new ArrayList<>();
String interm;
int start = 0;
for (int i = 1; i <= 3; i++) {
checkValidIP(s, start, start + i, 0, "", output));
}
return output;
}
}