leetcode 93 restore ip addresses


Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)


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
class  {
public List<String> restoreIpAddresses(String s) {
List<String> ans = new ArrayList<String>();
StringBuilder ip = new StringBuilder();

for(int A = 1; A <=3; A++){
for(int B = 1; B <=3; B++){
for(int C = 1; C <=3; C++){
for(int D=1; D <=3; D++){
if(A + B + C + D == s.length()){
int a = Integer.parseInt(s.substring(0, A));
int b = Integer.parseInt(s.substring(A, A+B));
int c = Integer.parseInt(s.substring(A+B, A+B+C));
int d = Integer.parseInt(s.substring(A+B+C));
if(a<=255 && b<=255 && c<=255 && d<= 255){
ip.append(a);
ip.append('.');
ip.append(b);
ip.append('.');
ip.append(c);
ip.append('.');
ip.append(d);

if(ip.length() == s.length() + 3){
ans.add(ip.toString());
}
ip.delete(0, ip.length());
}
}
}
}
}
}
return ans;
}
}