如何用Java编写程序来恢复IP地址?
- 内容介绍
- 文章标签
- 相关推荐
本文共计388个文字,预计阅读时间需要2分钟。
pythondef restore_ip_addresses(s: str) -> [str]: def is_valid(ip): return 0 <=int(ip) <=255 and ip.count('.')==3
def backtrack(start, path): if start==len(s) and len(path)==4: result.append(path) return for end in range(start + 3, min(start + 4, len(s) + 1)): ip=s[start:end] if is_valid(ip): backtrack(end, path + [ip])
result=[] backtrack(0, []) return result
示例input_str=25525511135output=restore_ip_addresses(input_str)print(output)
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。
本文共计388个文字,预计阅读时间需要2分钟。
pythondef restore_ip_addresses(s: str) -> [str]: def is_valid(ip): return 0 <=int(ip) <=255 and ip.count('.')==3
def backtrack(start, path): if start==len(s) and len(path)==4: result.append(path) return for end in range(start + 3, min(start + 4, len(s) + 1)): ip=s[start:end] if is_valid(ip): backtrack(end, path + [ip])
result=[] backtrack(0, []) return result
示例input_str=25525511135output=restore_ip_addresses(input_str)print(output)
给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

