题目
思路
分割
代码
class Solution:
def __init__(self):
self.res = []
self.path = []
def restoreIpAddresses(self, s: str):
self.backtracking(s, 0)
return self.res
def backtracking(self, s, start_index):
if len(self.path) == 4 and start_index == len(s):
self.res.append('.'.join(self.path[:]))
return
for i in range(start_index, len(s)):
t = s[start_index:i + 1]
# r = self.isValid(s,start_index,i)
r = self.isValid(t)
if r:
self.path.append(t)
self.backtracking(s, i + 1)
self.path.pop()
else:
break
def isValid(self, s: str) -> bool:
# 若数字是0开头,不合法
if s[0] == '0' and len(s) != 1:
return False
# 若不是0,255间的数字,不合法
if not 0 <= int(s) <= 255:
return False
return True
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
line = next(lines)
res = Solution().restoreIpAddresses(line)
print(res)
if __name__ == '__main__':
main()