-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathRestoreIP.java
33 lines (32 loc) · 1.01 KB
/
RestoreIP.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
public class Solution {
public ArrayList<String> restoreIpAddresses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<String> result = new ArrayList<String>();
exhaustIP(s, "", result, 4);
return result;
}
public void exhaustIP(String s, String ip, ArrayList<String> result, int piece){
if (piece == 1){
if (isValid(s)){
result.add(ip + s);
}
return;
}
for (int i = 1; i < 4 && i < s.length(); i++){
String part = s.substring(0, i);
if (isValid(part)){
exhaustIP(s.substring(i), ip + part + ".", result, piece - 1);
}
}
}
public boolean isValid(String part){
if (part.charAt(0) == '0') return part.length() == 1;
try{
int i = Integer.parseInt(part);
return 0 <= i && i <= 255;
}catch(Exception e){
return false;
}
}
}