题解 | #数字字符串转化成IP地址#
数字字符串转化成IP地址
https://www.nowcoder.com/practice/ce73540d47374dbe85b3125f57727e1e
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param s string字符串 # @return string字符串一维数组 # class Solution: def restoreIpAddresses(self , s: str) -> List[str]: # write code here res = [] ip = [] n = len(s) def backtrack(s): # IP接收数组满四个并且s为空,检查并存储结果 if len(ip) == 4 and s == '': ips = '.'.join(ip) if ips not in res: res.append(ips) return # 空字符s,或者s未用完但ip够了,不合法,返回 if s == '' or len(ip) == 4 and s != '': return # 回溯截取[1,2,3]长度的字符 for i in range(1, 4): sub = s[:i] # 排除不合法IP字段 if int(sub) > 255 or len(sub) > 1 and sub[0] == '0': continue ip.append(sub) backtrack(s[i:]) ip.pop() backtrack(s) return res