-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathRestoreIPAddresses.java
More file actions
52 lines (43 loc) · 1.13 KB
/
RestoreIPAddresses.java
File metadata and controls
52 lines (43 loc) · 1.13 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
public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String> re = new ArrayList<String>();
String[] sb = new String[4];
getIpAddresses(re, sb, s, 0);
return re;
}
public void getIpAddresses(ArrayList<String> re, String[] sb, String s, int level){
int len = s.length();
if(level<4 && (len<4-level || len>3*(4-level)))
return;
if(level == 4 && len>0)
return;
if(level ==4){
StringBuilder temp = new StringBuilder();
for(int i=0; i<4; i++){
temp.append(sb[i]);
temp.append('.');
}
temp.deleteCharAt(temp.length()-1);
re.add(temp.toString());
return;
}
if(s.charAt(0) == '0'){
sb[level] = "0";
getIpAddresses(re, sb, s.substring(1), level+1);
}
else{
for(int j=1; j<4; j++){
if(j<=len){
String stemp = s.substring(0,j);
int itemp = Integer.parseInt(stemp);
if(itemp<=255){
sb[level] = stemp;
getIpAddresses(re, sb, s.substring(j), level+1);
}
}
}
}
}
}