93. 复原 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
class Solution:
def __init__(self):
self.path = ""
def restoreIpAddresses(self, s: str) -> List[str]:
self.path = s
result = []
def Judge_legally(path,start,end) ->bool: # 判断是否合法
value = path[start:end]
is_or_not = True
if len(value)>3:
is_or_not=is_or_not and False
try: int(value)
except:
is_or_not=is_or_not and False
return is_or_not
if int(value)<0 or int(value)>255:
is_or_not=is_or_not and False
if len(value)>1 and value[0]=="0":
is_or_not=is_or_not and False
return is_or_not
def split_tree(start_index,split_count) ->List[str]: # 多叉树回溯分割
if split_count==3: # 确认到叶子结点
print("上一层 ",self.path)
if Judge_legally(self.path,start_index,len(self.path))==True:
print(self.path)
result.append(self.path)
return
for i in range(start_index,len(self.path)):
if Judge_legally(self.path,start_index,i+1)==True:
self.path = self.path[:i+1]+"."+self.path[i+1:]
split_count += 1
# print(self.path)
split_tree(i+2,split_count)
split_count -= 1
self.path = self.path[:i+1]+self.path[i+2:]
return result
return split_tree(0,0)