forked from vJechsmayr/PythonAlgorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0093_Restore_IP_address.py
More file actions
53 lines (36 loc) · 1.26 KB
/
Copy path0093_Restore_IP_address.py
File metadata and controls
53 lines (36 loc) · 1.26 KB
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
class Solution:
def restoreIpAddresses(self, s: str) -> list:
return self.convert(s)
def convert(self,s):
sz = len(s)
# Check for string size
if sz > 12:
return []
snew = s
l = []
# Generating different combinations.
for i in range(1, sz - 2):
for j in range(i + 1, sz - 1):
for k in range(j + 1, sz):
snew = snew[:k] + "." + snew[k:]
snew = snew[:j] + "." + snew[j:]
snew = snew[:i] + "." + snew[i:]
# Check for the validity of combination
if self.is_valid(snew):
l.append(snew)
snew = s
return l
def is_valid(self,ip):
# Splitting by "."
ip = ip.split(".")
# Checking for the corner cases
for i in ip:
if (len(i) > 3 or int(i) < 0 or
int(i) > 255):
return False
if len(i) > 1 and int(i) == 0:
return False
if (len(i) > 1 and int(i) != 0 and
i[0] == '0'):
return False
return True