LeetCode刷题之93.复原IP地址

LeetCode刷题之93.复原IP地址

我不知道将去向何方,但我已在路上!
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 !
  • 题目
    给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
  • 示例
输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]
  • 代码:
class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        if len(s)>12:
            return[]
        result = []
        import itertools
        b = [i for i in range(1,len(s))]
        a = itertools.combinations(b,3)
        for temp in a:
            a1 = s[:temp[0]]
            a2 = s[temp[0]:temp[1]]
            a3 = s[temp[1]:temp[2]]
            a4 = s[temp[2]:]
            if int(a1)>255 or int(a2)>255 or int(a3)>255 or int(a4)>255:
                continue
            if len(a1)>1 and a1[0] == '0':
                continue
            if len(a2)>1 and a2[0] == '0':
                continue
            if len(a3)>1 and a3[0] == '0':
                continue
            if len(a4)>1 and a4[0] == '0':
                continue
            result.append(a1 + "." + a2 + "." + a3 + "." + a4)
        return result
# 执行用时 :44 ms, 在所有 python3 提交中击败了92.13%的用户
# 内存消耗 :13.9 MB, 在所有 python3 提交中击败了5.15%的用户
  • 算法说明:
    首先排除IP地址长度大于12的情况;可以将题目转化为在长度不大于12的一串数中插入三个点,用itertools.combinations函数,在(1,len(s))范围内生成3个一组的组合数,用组合数将数据分为四个切片a1、a2、a3、a4,然后判断每一个切片的合法性,如果切片的值大于255,进行下一个分割方法的判断;在切片的长度不止一位时,如果切片的第一位为“0”,切片不合法,进行下一个分割方法的判断;其他情况则切片合法,根据组合数,在s的对应位置插入符号“.”之后,添加到result中,最后输出result。
发布了90 篇原创文章 · 获赞 1 · 访问量 1038

猜你喜欢

转载自blog.csdn.net/qq_34331113/article/details/103859031
今日推荐