字符串、回溯-LeetCode93. 复原IP地址

1、题目描述

https://leetcode-cn.com/problems/restore-ip-addresses/

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。

输入: "25525511135"
输出: ["255.255.11.135", "255.255.111.35"]

2、代码详解

暴力

class Solution(object):
    def restoreIpAddresses(self, s):
        n = len(s)
        res = []

        # 判读是否满足ip的条件
        def helper(tmp):
            # 每位是在0~255之间, 不能出现以0开头的两位以上数字
            if not tmp or (tmp[0] == "0" and len(tmp) > 1) or int(tmp) > 255:
                return False
            return True

        # 三个循环,把数字分成四份
        for i in range(3):
            for j in range(i + 1, i + 4):
                for k in range(j + 1, j + 4):
                    if i < n and j < n and k < n:
                        tmp1 = s[:i + 1]
                        tmp2 = s[i + 1:j + 1]
                        tmp3 = s[j + 1:k + 1]
                        tmp4 = s[k + 1:]
                        # print(tmp1, tmp2, tmp3, tmp4)

                        # all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE
                        # map(function, iterable, ...),返回包含每次 function 函数返回值的新列表
                        if all(map(helper, [tmp1, tmp2, tmp3, tmp4])):
                            res.append(tmp1 + "." + tmp2 + "." + tmp3 + "." + tmp4)
        return res

ss = "25525511135"
s = Solution()
print(s.restoreIpAddresses(ss))  # ['255.255.11.135', '255.255.111.35']

all()https://www.runoob.com/python/python-func-all.html

map()https://www.runoob.com/python/python-func-map.html

回溯

https://leetcode-cn.com/problems/restore-ip-addresses/solution/bao-li-he-hui-su-by-powcai/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值