• 93. Restore IP Addresses


    """
    93. Restore IP Addresses
    Medium
    473
    177


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

    Example:

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

    给定一个由数字组成的字符串判断加上"."以后可能构成的ip地址的集合

    ip地址是由四个0-255之间的数字构成的,除了0以外,首位不能为0

    这道题目的解题方法有很多,可以递归也可以暴力循环,我是用动规做的

    用一个字典记录具体的情况

    用(i,k)来记载截止索引为i的子字符串包含k个单个ip值的情况,也就是要求的是(len-1,4)的值.

    可以通过(len-2,3),(len-3,3),(len-4,3)计算得到

    上代码:

    class Solution:
    
        def isValidNum(self, s):
            """
            用来计算ip地址中间的某一个字符串是否合法
            """
            if not s.isdigit():
                return False
            if int(s) <= 255 and str(int(s)) == s:
                return True
            return False
    
        def getIndexValues(self, s, i, k, dict_kinds):
            """
            计算第i索引为结尾的字符串分成k个满足条件的数字的个数,并且加入到dict_kinds中
            """
            s_len = len(s)
            #长度不够
            if s_len < i+1:
                return
            #ip首位
            if k == 1:
                s1 = s[:i+1]
                if self.isValidNum(s1):
                    dict_kinds[(i, k)] = [s1]
            else:
                # print(k)
                l2 = []
                #新加入的ip的长度
                for j in range(1, 4):
                    l1 = dict_kinds.get((i-j, k-1), [])
                    s1 = s[i-j+1 : i+1]
                    if self.isValidNum(s1):
                        for s2 in l1:
                            s3 = ".".join([s2, s1])
                            l2.append(s3)
                if l2:
                    dict_kinds[(i, k)] = l2
    
        def restoreIpAddresses(self, s):
            """
            :type s: str
            :rtype: List[str]
            """
            s_len = len(s)
            dict_kinds = {}
            for i in range(s_len-1):
                for k in range(1, 4):
                    self.getIndexValues(s, i, k, dict_kinds)
            self.getIndexValues(s, s_len-1, 4, dict_kinds)
            result = dict_kinds.get((s_len-1, 4), [])
            return result
  • 相关阅读:
    夺命雷公狗TP3.2.3商城11-----后台头部和左侧导航分离
    夺命雷公狗TP3.2.3商城10-----中间层的创建,防止跨目录访问
    3.spring cloud eureka 高可用
    2.spring cloud eureka client配置
    1.spring cloud eureka server配置
    css去掉input记住密码的黄色
    34-THREE.JS 游泳圈
    32-THREE.JS 球体
    31-THREE.JS 正方体
    30-THREE.JS 圆环
  • 原文地址:https://www.cnblogs.com/mangmangbiluo/p/10095180.html
Copyright © 2020-2023  润新知