Restore IP Addresses

Leetcode 93.

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
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> addresses = new ArrayList<>();
StringBuilder tempAddress = new StringBuilder();
backtricking(s,addresses,tempAddress,0);

return addresses;
}
private void backtricking(String input,List<String> address,StringBuilder tempAddress,int k){
//recursion stop condition
if(k == 4 || input.length() == 0){
//collect result
if(k == 4 && input.length() == 0){
address.add(tempAddress.toString());
}
return;
}
//for loop : Set of elements in this layer
for(int i = 0; i < 3 && i < input.length();i++){
//process nodes according to the requirements
if(i != 0 && input.charAt(0) == '0'){
break;
}
String part = input.substring(0,i+1);
if(Integer.valueOf(part) <= 255){
if(tempAddress.length() != 0){
part = "." + part;
}
tempAddress.append(part);
//recursion
backtricking(input.substring(i+1),address,tempAddress,k+1);
//backtricking and undo the previous processing node
tempAddress.delete(tempAddress.length() - part.length(),tempAddress.length());
}

}

}
}