93_Restore IP Address
Input: "25525511135"
Output:["255.255.11.135", "255.255.111.35"]Solution 1: iterative
def restoreIpAddresses(s):
"""
:type s: str
:rtype: List[str]
"""
def is_valid_part(s):
return int(s) >= 256 or (len(s) >= 2 and s[0] == "0")
if len(s) > 12: return []
output = []
for i in range(len(s)-3):
if not is_valid_part(s[:i+1]):
for j in range(i+1, len(s)-2):
if not is_valid_part(s[i+1:j+1]):
for k in range(j+1, len(s)-1):
if not is_valid_part(s[j+1:k+1]) and not is_valid_part(s[k+1:]):
output.append(s[:i+1]+"."+s[i+1:j+1]+"."+s[j+1:k+1]+"."+s[k+1:])
return outputSolution 2: backtracking
Last updated