作者:手机用户2502853217 | 来源:互联网 | 2023-09-17 15:14
题目:
给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能从 s 获得的 有效 IP 地址 。你可以按 任何 顺序返回答案。
有效 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 地址。
![在这里插入图片描述](https://img.php1.cn/3cd4a/1eebe/cd5/d84f9786330d9e41.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5p-S5bm05pe25YWJ,size_20,color_FFFFFF,t_70,g_se,x_16)
解答:
class Solution:def restoreIpAddresses(self, s: str) -> List[str]:res&#61;[]path&#61;[]def tracebacking(s,startidx):nonlocal res,pathif startidx&#61;&#61;len(s) and len(path)&#61;&#61;4:res.append(&#39;.&#39;.join(path))for i in range(startidx,len(s)): if s[startidx]&#61;&#61;&#39;0&#39; and i!&#61;startidx:breaknum&#61;int(s[startidx:i&#43;1])if num>&#61;0 and num<&#61;255:path.append(s[startidx:i&#43;1])tracebacking(s,i&#43;1)path.pop()else:break n&#61;len(s)if n&#61;&#61;0 or n>12:return restracebacking(s,0)return res