本文共 1717 字,大约阅读时间需要 5 分钟。
解决这个问题,首先需要理解IP地址的结构。标准的IP地址由四个八位数字组成,每部分范围在0到255之间。给定一个字符串,我们需要将其分割成四个部分,每个部分都必须是一个有效的八位数。
我们可以使用暴力法来尝试所有可能的分割方式。具体步骤如下:
class Solution(object): def restoreIpAddresses(self, s): """Return a list of all possible IP addresses from the given string.""" if not s or len(s) > 12 or len(s) < 4: return [] result = [] for a in range(1, 4): for b in range(1, 4): for c in range(1, 4): for d in range(1, 4): if a + b + c + d != len(s): continue parts = [ s[:a], s[a:a+b], s[a+b:a+b+c], s[a+b+c:a+b+c+d] ] try: ip = [ int(part) for part in parts ] except: continue if all(0 <= x <= 255 for x in ip): ip_str = '.'.join(map(str, ip)) if ip_str not in result: result.append(ip_str) return result
result。这种方法虽然简单,但在实际应用中效率尚可,特别是当字符串长度较短时。
转载地址:http://vufo.baihongyu.com/