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)
给一个字符串,转成可能组成的IP数
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
|
public
class
Solution
{
//深度优先遍历,DFS即可实现
List<String> res=
new
ArrayList<String>();
public
List<String> restoreIpAddresses(String s)
{
//特殊情况处理
if
(s==
null
|| s.length()<=
0
|| s.length()<
4
|| s.length()>
12
)
return
res;
String one=
""
;
byDFS(s,
0
,
0
,one);
return
res;
}
//index 记录开始的位置,k记录截取的数量,
void
byDFS(String s,
int
index,
int
k,String one)
{
if
(k==
3
)
{
String tmp = s.substring(index, s.length());
if
(check(tmp))
res.add(one+tmp);
return
;
}
else
{
//每一次最长的截取长度是i,最短1位,最长3位
for
(
int
i=
1
;i<=
3
&& index+i < s.length() ;i++)
{
String tmp = s.substring(index, index+i);
if
(check(tmp))
byDFS(s, index+i, k+
1
, one+tmp+
"."
);
}
}
}
public
boolean
check(String ip)
{
//以0开始的字符串,只有0是合理的,其余的比如001等等都不是合理的
if
(ip.charAt(
0
)==
'0'
)
{
if
(ip.equals(
"0"
))
return
true
;
else
return
false
;
}
else
{
int
ipNum=Integer.parseInt(ip);
if
(ipNum>
0
&& ipNum<=
255
)
return
true
;
else
return
false
;
}
}
}
|
哎,映客线下笔试题。好难哦。虽然想到是回溯,但是没做出来,没想到是LT原题。gg。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1971550