题目
题目链接
给出一个纯数字字符串,将字符串分割为合法的ip地址,返回所有可能的情况
思路
判断ip地址的一部分是否合法
- 需要在0~255之间
- 不能有前导0,如02、002不合法(但只有一个0为合法)
- 不能为空
递归回溯
使用三个参数s,cell,IPs
s
:剩余的还未使用的字符串
cell
:本次递归已经生成的ip地址数组,内含0-4个合法的数字
IPs
:存放所有已生成的合法ip数组
递归结束的条件
:
cell
中有4个合法的数字,且s
中没有剩余的数字,则把cell
加入IPs
中,退递归
递归中的操作
:
从字符串首部开始,循环检查1~3个连续的数字 :
- 若当前的数字合法,把该数字加入
cell
- 将
s
中剩下的数字继续递归 - 递归结束后,把刚才加入
cell
的数字移出(回溯)
代码
class Solution:
# 判断当前数字是否合法
def isOK(self, s):
if not s: #不能为空
return False
if len(s) > 1 and s[0] == '0': #不能有前导0
return False
if int(s) > 255: #不能大于255
return False
return True
# 根据4个数字,生成带点的ip地址字符串
def makeIP(self,s):
ip=''
for i in range(3):
ip+=s[i]+'.'
return ip+s[-1]
# dfs递归回溯
def dfsIP(self, s, cell, IPs):
if len(cell) == 4 and not s: # 已有4个数字,且没有剩下未使用的数字
IPs.append(self.makeIP(cell))
return
# 取长度1-3的数字检查
for i in range(0, len(s)):
if i == 3:
break
# 若合法,加入cell
if self.isOK(s[:i + 1]):
cell.append(s[:i + 1])
# 把剩下的数字递归
self.dfsIP(s[i + 1:], cell, IPs)
# 退递归之后回溯
cell.pop()
def restoreIpAddresses(self, s):
cell, IPs = [], []
self.dfsIP(s, cell, IPs)
return IPs