IPアドレスの復元
3371 ワード
タイトルの説明
数値のみを含む文字列を指定し、それを復元し、可能なすべてのIPアドレスフォーマットを返します.例:
入力:255,511,135
出力:["255.255.1.135","255.255.11.35"]
問題を解く構想.
DFS.多くの枝を組み合わせると、スピードが速くなります.
コード#コード#
Python 3.6
[Python]
テキスト表示
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
詳細については、gzitcast
数値のみを含む文字列を指定し、それを復元し、可能なすべてのIPアドレスフォーマットを返します.例:
入力:255,511,135
出力:["255.255.1.135","255.255.11.35"]
問題を解く構想.
DFS.多くの枝を組み合わせると、スピードが速くなります.
コード#コード#
Python 3.6
[Python]
テキスト表示
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class
Solution:
def
restoreIpAddresses(
self
, s:
str
)
-
>
List
[
str
]:
length
=
len
(s)
if
length <
4
or
length >
12
:
return
[]
res
=
[]
self
.__dfs(s,
0
, length, [], res)
return
res
def
__dfs(
self
, s, start, length, path, res):
blank
=
4
-
len
(path)
if
blank
=
=
0
:
if
start >
=
length:
res.append(
"."
.join(path.copy()))
return
if
(length
-
start < blank)
or
(length
-
start >
3
*
blank):
# 3*
return
for
i
in
range
(
1
,
4
):
end
=
start
+
i
if
end > length
or
int
(s[start:end]) >
255
or
(i >
1
and
s[start:end][
0
]
=
=
"0"
):
# : 255、 0
break
path.append(s[start:end])
self
.__dfs(s, end, length, path, res)
path.pop()
詳細については、gzitcast