-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrestoreIP.java
More file actions
29 lines (29 loc) · 948 Bytes
/
restoreIP.java
File metadata and controls
29 lines (29 loc) · 948 Bytes
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
public class Solution {
ArrayList<String> result;
public ArrayList<String> restoreIpAddresses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
result=new ArrayList<String>();
build("",s,4);
return result;
}
public void build(String current,String rest,int empty) {
if(rest.length()>empty*3||rest.length()<empty||rest.equals("")) return;
if(empty==1) {
if(isValid(rest))
result.add(current+rest);
return;
}
for(int i=1;i<=Math.min(rest.length(),3);i++) {
String c=rest.substring(0,i);
if(isValid(c))
build(current+c+".",rest.substring(i),empty-1);
}
}
public boolean isValid(String s) {
if(s.length()>1&&s.charAt(0)=='0') return false;
int i=Integer.parseInt(s);
if(i>=0&&i<=255) return true;
return false;
}
}