Valid IP Address

Posted LilyLiya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于Valid IP Address的主要内容,如果未能解决你的问题,请参考以下文章

connect: Address is invalid on local machine or port is not valid on remote

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:8888(代码片段

判断IP地址与掩码是否合法程序

问题解决:Cannot assign requested address

拥有的50个CSS代码片段(上)

1108. IP 地址无效化