• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LilyLiya
博客园    首页    新随笔    联系   管理    订阅  订阅
Valid IP Address
check leading zero: stringAsInt = int(string) return len(string) == len(str(stringAsInt)) join strings from a list together (".".join())

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

 
posted on 2021-06-02 06:21  LilyLiya  阅读(86)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3