-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathrestore-ip-addresses.py
More file actions
35 lines (26 loc) · 970 Bytes
/
restore-ip-addresses.py
File metadata and controls
35 lines (26 loc) · 970 Bytes
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
from typing import List
class Solution:
def restoreIpAddresses(self, string: str) -> List[str]:
result: List[str] = []
stack: List[str] = []
def dfs(pos: int, blocks: int) -> None:
if pos == len(string):
if blocks == 4:
result.append("".join(stack))
return
if blocks == 4:
return
for next_pos in range(pos + 1, min(len(string) + 1, pos + 4)):
substring = string[pos:next_pos]
if 0 <= int(substring) < 256 and not (
len(substring) > 1 and substring[0] == "0"
):
if stack:
stack.append(".")
stack.append(substring)
dfs(next_pos, blocks + 1)
stack.pop()
if stack:
stack.pop()
dfs(0, 0)
return result