Valid IP Address

refer to: https://www.algoexpert.io/questions/Valid%20IP%20Addresses

Problem statement

 

Analysis

 Code

def validIPAddresses(string):
    ipAddressesFound = []
    
    for i in range(1, min(len(string), 4)):
        currentIPAddressParts = ["", "", "", ""]
        
        currentIPAddressParts[0] = string[:i] # the first part
        if not isValidPart(currentIPAddressParts[0]):
            continue
            
        for j in range(i + 1, i + min(len(string) - i, 4)):
            currentIPAddressParts[1] = string[i:j] # the second part
            if not isValidPart(currentIPAddressParts[1]):
                continue
                
            for k in range(j + 1, j + min(len(string) - j, 4)):
                currentIPAddressParts[2] = string[j:k] # the third part
                currentIPAddressParts[3] = string[k:]  # the forth part
                
                if isValidPart(currentIPAddressParts[2]) and isValidPart(currentIPAddressParts[3]):
                    ipAddressesFound.append(".".join(currentIPAddressParts))
    return ipAddressesFound

def isValidPart(string):
    stringAsInt = int(string) # leading zero will be removed
    if stringAsInt > 255:
        return False
    return len(string) == len(str(stringAsInt)) # check for leading zeros

Time and space complexity

 O(1) time 8 bits * 4 = 32 bits. 2^(32) possibilities  (0. 1)

O(1)  space 2^(32) possibilities

 
原文地址:https://www.cnblogs.com/LilyLiya/p/14839648.html