Leetcode 93:复原IP地址(最详细的解法!!!)

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

示例:

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

解题思路

我们知道IP地址分为四个小段,每一小段都是在0~255这个区间内(第一小段不能为0)。这个问题和Leetcode 17:电话号码的字母组合(最详细的解法!!!)非常类似,写法上也很相像。这个问题中,对于有效数字的判断存在一个陷阱

def isNum(num):
    if 0 <= int(num) <= 255:
        return True
    return False

但是这种写法,会出现这样的问题,对于001,也会判断为有效数,实际上这是不对的。我们应该这样写

def isNum(num):
    if 0 <= int(num) <= 255 and str(int(num)) == num:
        return True
    return False

这个问题中还有一个小的细节,就是我们对于前三段做一样的处(结尾加 .),而最后一段单独考虑,所以这就变成了边界条件之一。

class Solution:
    def _restoreIpAddresses(self, s, n, index, ip, result):
        if n == 0:
            if index == len(s):
                result.append(ip)
            return

        def isNum(num):
            if 0 <= int(num) <= 255 and str(int(num)) == num:
                return True
            return False

        for i in range(index+1, len(s) + 1):
            if isNum(s[index:i]):
                self._restoreIpAddresses(s, n - 1, i, s[index:i] if ip == "" else ip+'.'+s[index:i], result)
            else:
                break
                   
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """
        result = list()
        if not s or  4 > len(s) or len(s) > 12 :
            return result

        self._restoreIpAddresses(s, 4, 0, "", result)
        return result

同样的,对于递归可以解决的问题,我们都应该思考是不是可以通过迭代解决。

class Solution:
    def restoreIpAddresses(self, s):
        """
        :type s: str
        :rtype: List[str]
        """      
        def isNum(num):
            if num and 0 <= int(num) <= 255 and str(int(num)) == num:
                return True
            return False
        
        result = list()
        for i in range(1, 4):
            w1 = s[:i]
            if not isNum(w1):
                continue

            for j in range(i+1, i+4):
                w2 = s[i:j]
                if not isNum(w2):
                    continue

                for k in range(j+1, j+4):
                    w3, w4 = s[j:k], s[k:]
                    print(w3, w4)
                    if not isNum(w3) or not isNum(w4):
                        continue

                    result.append(w1 + '.' + w2 + '.' + w3 + '.' + w4)

        return result

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值