給定一個只包含數字的字符串,復原它並返回所有可能的 IP 地址格式。
有效的 IP 地址正好由四個整數(每個整數位於 0 到 255 之間組成),整數之間用 ‘.’ 分隔。
public List<String> restoreIpAddresses(String s) {
return restoreIpAddresses(s, 4);
}
private List<String> restoreIpAddresses(String s, int n) {
List<String> res = new ArrayList<>();
if (s.length()<n) return res;
if (n==1) {
if (s.length() == 1 || ( s.startsWith("0") == false && s.length()<4)) {
int x = Integer.valueOf(s);
if (x>=0 && x<=255) {
res.add(s);
}
}
} else {
String head = s.substring(0, 1);
List<String> r = restoreIpAddresses(s.substring(1), n-1);
for(String e: r) {
res.add(head+"." +e);
}
head = s.substring(0, 2);
if (!head.startsWith("0")) {
r = restoreIpAddresses(s.substring(2), n-1);
for(String e: r) {
res.add(head+"." +e);
}
}