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

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/82460013

给定一个只包含数字的字符串,复原它并返回所有可能的 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 and  4 > 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

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

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/82460013