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)
public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
StringBuilder sb = new StringBuilder();
int len = s.length();
for (int a = 1; a < 4; a ++)
for (int b = 1; b < 4; b ++)
for (int c = 1; c < 4; c ++)
for (int d = 1; d < 4; d ++) {
if (a + b + c + d == len) {
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, a + b + c + d));
if (A <= 255 && B <= 255 && C <= 255 && D <= 255) {
sb.append(A).append('.').append(B).append('.').append(C).append('.').append(D);
if (sb.length() == len + 3)
res.add(sb.toString());
sb.delete(0, sb.length());
}
}
}
return res;
}
}