""" 测试用例
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)
06-09
5162