1、题目描述
有效 IP 地址 正好由四个整数(每个整数位于 0
到 255
之间组成,且不能含有前导 0
),整数之间用 '.'
分隔。
- 例如:
"0.1.2.201"
和"192.168.1.1"
是 有效 IP 地址,但是"0.011.255.245"
、"192.168.1.312"
和"192.168@1.1"
是 无效 IP 地址。
给定一个只包含数字的字符串 s
,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s
中插入 '.'
来形成。你 不能 重新排序或删除 s
中的任何数字。你可以按 任何 顺序返回答案。
示例 1:
输入:s = "25525511135" 输出:["255.255.11.135","255.255.111.35"]
2、初始思路
2.1 思路
首先,可以明确,本题是分割问题,因此,我们可以根据分割子串的思路进行思考。
1、分割成什么格式?
有效 IP 地址 由四个整数(每个整数位于 0
到 255
之间组成,且不能含有前导 0
),整数之间用 '.'
分隔。
- 四个整数片段
- 每个整数位于0-255之间
- 不能含有前导0
- 整数之间用‘.'分割
根据上述条件,可以给出一个对子串进行合理化判断的函数:
def is_valid(substr):
if len(substr) == 0 or len(substr) > 3:
return False
if substr[0] == '0' and len(substr) != 1:
return False
return 0 <= int(substr) <= 255
2、如何进行分割?
从头进行分割,当子串符合合理化要求时,才可将其加入到path中
for i in range(start_index, min(start_index + 3, len(s))):
substr = s[start_index:i+1]
if is_valid(substr):
path.append(substr)
backtrack(i + 1, segments + 1)
path.pop()
3、终止条件是什么?
当分割为四个子串,并且已经切割到末尾时,此时整个分割结束,可将path加入到结果中。
if segments == 4:
if start_index == len(s):
res.append('.'.join(path))
return
2.2 完整代码
class Solution:
def restoreIpAddresses(self, s: str) -> List[str]:
path = []
res = []
def isvalid(substr):
if len(substr) > 3 or len(substr) == 0:
return False
if int(substr) < 0 or int(substr) > 255:
return False
if len(substr) >1 and substr[0] == '0':
return False
return True
def backtracking(s,startIndex,segments):
if segments == 4:
if startIndex == len(s):
res.append('.'.join(path.copy()))
return
for i in range(startIndex, min(startIndex + 3,len(s))):
substr = s[startIndex:i+1]
if isvalid(substr):
path.append(substr)
backtracking(s,i+1,segments+1)
path.pop()
if 4<=len(s)<=12:
backtracking(s,0,0)
return res