Leetcode练习(python):字符串类:第93题:复原IP地址:给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。 有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。

题目:
复原IP地址:给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。  有效的 IP 地址正好由四个整数(每个整数位于 0 到 255 之间组成),整数之间用 '.' 分隔。 
思路:
思路较简单。
程序:
class Solution:
    def restoreIpAddresses(self, s: str) -> List[str]:
        if not s:
            return []
        length = len(s)
        if length < 4:
            return []
        result = []
        for index1 in range(1, 4):
            section1 = s[0: index1]
            if self.judgeIfValid(section1):
                for index2 in range(index1 + 1, index1 + 4):
                    section2 = s[index1: index2]
                    if self.judgeIfValid(section2):
                        for index3 in range(index2 + 1, index2 + 4):
                            section3 = s[index2: index3]
                            if self.judgeIfValid(section3):
                                section4 = s[index3:]
                                if self.judgeIfValid(section4):
                                    result.append("%s.%s.%s.%s" %(section1, section2, section3, section4))
        ip = result
        return ip
    def judgeIfValid(self, section):
        if section and section[0] == "0"  and len(section) > 1:
            return False
        if section and int(section) == 0 and len(section) > 1:
            return False
        if section and len(section) > 3:
            return False
        if section and int(section) >= 0 and int(section) <= 255:
            return True
        else:
            return False
原文地址:https://www.cnblogs.com/zhuozige/p/12849342.html