leetcode solution

https://leetcode.com/problems/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)

Keywords: ALL POSSIBLE gives us hint to use DFS

Another important point is that we should eliminate the case like '00', '01', '001', etc.

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
53
54
55
56
57
58

public class {

* @param s the IP string
* @return All possible valid IP addresses
*/

public ArrayList<String> restoreIpAddresses(String s) {
// Write your code here
char[] str = s.toCharArray();
int pointNums = 0;
ArrayList<String> result = new ArrayList<String>();
String temp = new String();

if (s == null || s.length() < 4 || s.length() > 12) {
return result;
}
restoreIpAddressesHelper(result, temp, str, 0, pointNums);
return result;
}

private void restoreIpAddressesHelper(ArrayList<String> result,
String temp,
char[] str,
int pos,
int pointNums)
{

if (temp.length() == str.length + 3 && pointNums == 3) {
result.add(temp);
}
if (pointNums > 3) {
return;
}

StringBuffer addString = new StringBuffer();
for (int i = pos; i < pos + 3 && i < str.length; i++) {
addString.append(str[i]);
if (!isValidHelper(addString.toString())) {
break;
}
if ( i == str.length - 1) {
restoreIpAddressesHelper(result, temp + addString,
str, i + 1, pointNums);
} else {
restoreIpAddressesHelper(result, temp + addString + ".",
str, i + 1, pointNums + 1);
}
}
return;
}
private boolean isValidHelper(String s) {
if (s.charAt(0) == '0' && s.length() != 1) {
return false;
} else if (Integer.valueOf(s) > 255 ) {
return false;
} else {
return true;
}
}
}