复原IP地址

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

有效的 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 ‘.’ 分隔。

例如:”0.1.2.201” 和 “192.168.1.1” 是 有效的 IP 地址,但是 “0.011.255.245”、”192.168.1.312” 和 “192.168@1.1“ 是 无效的 IP 地址。

示例 1:

1
2
输入:s = "25525511135"
输出:["255.255.11.135","255.255.111.35"]

示例 2:

1
2
输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

1
2
输入:s = "1111"
输出:["1.1.1.1"]

示例 4:

1
2
输入:s = "010010"
输出:["0.10.0.10","0.100.1.0"]

示例 5:

1
2
输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

提示:

  • 0 <= s.length <= 3000
  • s 仅由数字组成

代码:

第一次提交(29%时,68%空)

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
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> list=new LinkedList<String>();
if(s==null||s.length()==0||s.length()>12)return list;
return restore(s,4);
}
//在字符串中插入多少个点,能符合IP地址,0-255,不含前导0
public List<String> restore(String s,int num)
{
List<String> list=new LinkedList<String>();
if(s==null||s.length()==0)return list;

if(num==1)
{
if(s.length()>3)return list;
if(Integer.valueOf(s)>255)return list;
if(s.charAt(0)=='0'&&s.length()>1)return list;
list.add(s);
return list;
}else
{
//第一个就是0,直接下点
if(s.charAt(0)=='0')
{
List<String> lstemp=restore(s.substring(1),num-1);
if(lstemp==null||lstemp.size()==0)return list;
for(String v:lstemp)
{
list.add("0."+v);
}
return list;
}
else
{
for (int i = 0; i < 3&&i<s.length(); i++) {
String temp=s.substring(0,i+1);
if(Integer.valueOf(temp)>255)
{
//这个不行
continue;
}
else
{
List<String> lstemp=restore(s.substring(i+1),num-1);
if(lstemp==null||lstemp.size()==0)continue;
for(String v:lstemp)
{
list.add(temp+"."+v);
}
}
}
}
}
return list;
}
}