【算法】给定一个数字组成的字符串,返回有多少种合法的 IPV4 组合

""" 测试用例
245111
11111
100111
10137171
"""
# 方法一、逐部分判断
class Solution:
    def restoreIpAddresses(self, s: 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

string = input()
res = Solution()
r = res.restoreIpAddresses(string)
print(r)


# 方法二、各部分长度渐增,等于原长时判断
s= string
res = []
if len(s)>12 or len(s)<4:
    print("error")
for i in range(1, 4):
    for j in range(1, 4):
        for k in range(1, 4):
            for m in range(1, 4):
                s1 = s[0:i]
                s2 = s[i:i+j]
                s3 = s[i+j:i+j+k]
                s4 = s[i+j+k:i+j+k+m]
                if len(s) == i+j+k+m and (int(s1) <= 255) and \
                        (int(s2)<=255) and (int(s3)<=255) and (int(s4) <= 255):
                    if (len(s1)>1 and s1[0]=='0') or (len(s2)>1 and s2[0]=='0') or (len(s3)>1 and s3[0]=='0') or (len(s4)>1 and s4[0]=='0'):
                        break
                    else:
                        res.append("%s.%s.%s.%s" % (s1, s2, s3, s4))

print(res)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值