LeetCode 93.复原IP地址

本文介绍了一种通过递归方法解决复原IP地址问题的技术。利用递归遍历字符串的所有可能组合,验证每种组合是否符合有效的IP地址格式,并将符合条件的组合添加到结果列表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/restore-ip-addresses

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

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

例如:"0.1.2.201" 和 "192.168.1.1" 是 有效的 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效的 IP 地址。

示例 1:

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

示例 2:

输入:s = "0000"
输出:["0.0.0.0"]

示例 3:

输入:s = "1111"
输出:["1.1.1.1"]

示例 4:

输入:s = "010010"
输出:["0.10.0.10","0.100.1.0"]

示例 5:

输入:s = "101023"
输出:["1.0.10.23","1.0.102.3","10.1.0.23","10.10.2.3","101.0.2.3"]

解题思路:第一个想法就是每次选择一个、两个、或者三个数字并以它们为基础进行递归直到由四个整数构成一个地址并判断是否有效,如果有效就加入result,AC代码如下:

class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        result = []
        temp = ""
        length = len(s)
        self.calculate(s, 0, temp, result, length, 0)
        for i in range(len(result)):
            result[i] = result[i][:len(result[i]) - 1]
        return result

    def calculate(self, s: str, location: int, temp: str, result: List[str], length: int, count: int):
        if count == 4:
            if location == length:
                result.append(temp)
            return
        else:
            if location < length and s[location] == "0":
                temp += "0."
                self.calculate(s, location + 1, temp, result, length, count + 1)
            else:
                self.calculate(s, location + 1, temp + s[location:location + 1] + ".", result, length, count + 1)
                if location + 2 <= length:
                    self.calculate(s, location + 2, temp + s[location:location + 2] + ".", result, length, count + 1)
                if location + 3 <= length and s[location:location + 3] <= "255":
                    self.calculate(s, location + 3, temp + s[location:location + 3] + ".", result, length, count + 1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值