93. Restore IP Addresses[M]

https://leetcode.com/problems/restore-ip-addresses/

Description

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

A valid IP address consists of exactly four integers (each integer is between 0 and 255) separated by single points.

Example:

1
2
Input: "25525511135"
Output: ["255.255.11.135", "255.255.111.35"]

Solution

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
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
ls = len(s)
if ls == 0 or ls > 12:
return []
res = []
for i in range(1, 4):
for j in range(1, 4):
for k in range(1, 4):
m = ls - i - j - k
if m > 0 and m <= 3:
add1 = s[0:i]
add2 = s[i:i + j]
add3 = s[i + j:i + j + k]
add4 = s[i + j + k:]
if self.isValid(add1) and self.isValid(add2) and \
self.isValid(add3) and self.isValid(add4):
res.append(add1 + '.' + add2 + '.' + add3 + '.' + add4)
return res

def isValid(self, add):
if len(add) == 1:
return True
if add[0] == '0':
return False
if int(add) <= 255:
return True
return False