LeetCode 93. Restore IP Addresses--面试算法题--Python解法

本文介绍了一道LeetCode上的算法题“恢复IP地址”的解题思路与Python实现。题目要求从一串数字中恢复所有可能的有效IP地址组合。文章详细解释了使用递归而非三重循环的方法,并提供了完整的Python代码。

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

题目地址:Restore IP Addresses - LeetCode


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"]

这道题目是XX的面试时出的算法题。难度不大,当时我是打算用三个for循环来解决这个问题。结果面试官说你用三个for循环太土了,用递归吧。
然后我用递归写了一遍。递归写起来比直接For循环更长,代码也更不好看,花的时间也挺多的。事后想起来当时我应该怼回去的,坚持用3个for循环写。

Python解法如下:

class Solution:
    def restoreIpAddresses(self, s: str):
        result = []
        length = len(s)
        if length == 0:
            return result
        for i in range(1, 4):
            if int(s[:i]) > 255 or(i > 1 and s[0] == '0'):
                continue
            for j in range(1, 4):
                if i+j > length or int(s[i:i+j]) > 255 or(j > 1 and s[i] == '0'):
                    continue
                for k in range(1, 4):
                    if i+j+k >= length or int(s[i+j:i+j+k]) > 255 \
                            or int(s[i+j+k:]) > 255 or (k > 1 and s[i+j] == '0') or(length-i-j-k > 1 and s[i+j+k] == '0'):
                        continue
                    result.append(s[:i]+'.'+s[i:i+j]+'.' +
                                  s[i+j:i+j+k]+'.'+s[i+j+k:])
        return result

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值